如何使用for循环替换字符?

时间:2016-02-04 02:06:41

标签: for-loop

我遇到的问题是for循环不检查整个单词。相反,它只在提供的索引处检查它。我需要它能够检查这些字母的任何实例的任何单词,并用相应的符号替换它们。我如何检查整个单词以寻找我要改变的字母。这是我迄今为止所能得到的:

 cout << "Enter word: ";
   cin >> userInput;
   cout << "You entered: " ;
   cin >> userInput;

   for (unsigned i=0; userInput.size() > i; i++){
      if (userInput.at(0)=='a'){
        userInput.at(0)=='@';
      }
      if (userInput.at(1)=='e'){
        userInput.at(1)=='3';
      }
      if (userInput.at(2)=='i'){
        userInput.at(2)=='!';
      }
       if (userInput.at(3)=='g'){
         userInput.at(3)=='9';
      }
       if (userInput.at(4)=='s'){
         userInput.at(4)=='$';
      }
       if (userInput.at(5)=='x'){
     userInput.at(5)=='*';
      }

   }
   cout << "New word: ";
   cout << userInput;

1 个答案:

答案 0 :(得分:0)

看起来你正试图用'@'替换所有'a',依此类推。在编写代码时,它只会考虑a - &gt;的第一个字符。 @替换,第二个字符用e - &gt; 3替换等

一些快速的事情。使用==测试进行相等性。您确实希望最初测试相等性,但稍后您还想执行一项任务(=)。

其次,您可能希望逐个字符地查看。根据要替换的值测试每个字符。 userInput.at(i)处的值是循环迭代的字符。

   for (unsigned i=0; userInput.size() > i; i++) {
      // Note, we're indexing based on the variable i, 
      // instead of a hard-coded number value
      if (userInput.at(i) == 'a') {

        // Note the single = on the line below
        userInput.at(i) = '@';
      }

      if (userInput.at(i) == 'e') {
        userInput.at(i) = '3';
      }

      // and so on
   }
相关问题