0

Is there any other method to change the first letter and last letter of a 6 letter word?

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string word;
    cout<< "\nEnter a 6 letter word or numbers: ";
    cin>>word;
    word[0]++;
    word[5]++;
    cout << "Result: " << word << endl;

    return 0;
}
  • what do you mean? Yes there are other ways. What is wrong with the way you are using now? – 463035818_is_not_an_ai Sep 28 '20 at 07:51
  • I was given a suggestion to use if/else or setw, is that possible? – scotts prod Sep 28 '20 at 07:51
  • @idclev463035818 I need 2-3 methods for it. That's the most simple one that came into my mind. – scotts prod Sep 28 '20 at 07:52
  • 1
    Well, for starters, you could use an `if` to check if the word has been actutally read and if it has at least 6 letters. Have you already been introduced to iterators? How many member functions of [`std::string`](https://en.cppreference.com/w/cpp/string/basic_string) do you know? – Bob__ Sep 28 '20 at 07:57
  • 2
    Can you please clarify what you are trying to achieve? – Lukas-T Sep 28 '20 at 08:00
  • @churill, I am trying to achieve a different method to change the first letter and last letter of a word to its next.. I'm trying to build it in if/else but don't know how to change its first and last letter. – scotts prod Sep 28 '20 at 08:04
  • Sorry, I don't get it. How do you want to use `if/else` here? And why would it change the way you change the first and last character? Is something not working in your program? I smell a [XY-Problem](http://xyproblem.info/). – Lukas-T Sep 28 '20 at 08:08

1 Answers1

1

you could also use string::replace but it is a pretty roundabout way compared to replacing using the subscript operator.

something like

#include <iostream>
#include <string>
using namespace std;

    int main()
    {
        string word;
        cout<< "\nEnter a 6 letter word or numbers: ";
        cin>>word;
        cout<<word;

        string repl = "x";
        word.replace(5,1, repl);      //replace the 5th position with 1 
                                              //character using string repl

        cout << "Result: " << word << endl;
    
        return 0;
    }

Take a look at http://cplusplus.com/reference/string/string/replace/

C++, best way to change a string at a particular index

How to replace one char by another using std::string in C++?

pcodex
  • 1,812
  • 15
  • 16