Home > Enterprise >  I'm trying to change every letter in a given string with the letter following it in the alphabe
I'm trying to change every letter in a given string with the letter following it in the alphabe

Time:02-20

#include<iostream>

#include<string>

using namespace std;

string pass(string a){

    int i=0;
    string c[100];
    char d;
    
    while(a[i]!='\0'){
     
     d = a[i];

     if(d>='a'&& d<='z'){
         d  ;
         c[i]=d;
     }
     else if(d>='A' && d<='Z'){
         d  ;
         c[i]=d;
     }
     else{
           c[i]=d;
     }
     i  ;
    }
    
    for(int k=0; k<i; k  ){
        cout<<c[k];
    }

    
    }



int main(){

string x;

getline(cin,x);

pass(x);
    return 0;
}

This is my solution.

I was looking for this kind of problem for a while but all I got pre-define inputs.

so, I passed a string from the main function

used while loop to store every letter with the following letter (EX "a -> b") in another array "c".

and print the copied array using a loop.

can we make it short?

CodePudding user response:

You don't need to create a separate array called c. You can create an output string and iterate through it and increment the characters as shown below:

int main()
{
    std::string input;
    std::getline(std::cin, input); 
    
    std::string output(input);
    for(char &c: output)
    {
          c;
    }
    std::cout<<"input was: "<<input<<std::endl;
    
    std::cout<<"changed string is: "<<output<<std::endl;
    
}

CodePudding user response:

This is probably a better (and shorter) implementation for your code:

#include<iostream>
#include<string>

char NextAlpha(char character)
{
    if (character == 'Z') return 'A';
    else if (character == 'z') return 'a';

    return character   1; // Can be replaced by 'char((int)character   1);'
}

int main() {

    std::string input;

    getline(std::cin, input);

    for (int i = 0; i < input.size(); i  )
    {
        input[i] = NextAlpha(input[i]);
    }

    std::cout << input;
    return 0;
}

The NextAlpha function returns the next alphabet by adding 1 to the character, but a more understandable version of it will be firstly converting the given character into an int as such:

(int)character

..which basically means getting the ascii value of that character. Now we add 1 to the int:

(int)character   1

..and then convert it back to char

char((int)character   1)

..but here I've not used this way because character looks a lot more cleaner.

The exceptions are defined before the return statement.

In the main function, we have a loop that iterates through all of the characters in the given string, and for each character, it does the following:

// Set the character at index 'i' of string 'input' to the next character in the alphabet.
input[i] = NextAlpha(input[i]); 

Also, consider not using the following in your code:

using namespace std;

..as it's considered as bad practice.

  •  Tags:  
  • c
  • Related