Peter Hwang
Peter Hwang

Reputation: 1

How to ignore white space and marks when encrypting a string variable in c++

I am trying to encrypt a string with white space and a question mark on it, for example, I am going to encrypt all the alphabet into numbers based on the order of the alphabet, but when I turn the string into numbers white space and question mark also gets enumerated how do I ignore that? example)

int main() {
  string alphabet;
  int encrypted_code;
  int first_int = 1, second_int = 2, third_int = 3;
  string text = "hey what is your name?";
  for (char ch = 'a'; ch <= 'z'; ch++) {
    alphabet += ch;
  }
  for (int i = 0; i < text.length(); i++) {
    encrypted_code = alphabet.find(text[i]);
    if (i == 0 || i % 3 == 0) {
      encrypted_code = encrypted_code + first_int;
    }
    cout << encrypted_code << " ";
  }
}

Upvotes: 0

Views: 167

Answers (1)

David G
David G

Reputation: 96810

Use an if statement to only work on letters:

for (int i = 0; i < text.length(); i++) {
  if ('a' <= text[i] && text[i] <= 'z') {
    // rest of your code goes here
  }
}

Upvotes: 2

Related Questions