c++ - 在C++中交换短语中单词的前两个字母

标签 c++

如何让 for 循环交换短语中每个单词的前两个字符?

int main() {
 cout << "Enter a phrase" << endl;
 char phrase[30];
 cin.get(phrase, 30);
 int temp;
 for (int i = 0; i < strlen(phrase); i++) {
  for (int j = i+1; j < strlen(phrase); j++) {
      int k = j+1;
      //Start of for loop
      if (i == 0 && j == 1) {
          phrase[i] = temp;
          phrase[i] = phrase[j];
          phrase[j] = temp;
      }
      if (phrase[i] == '\0' || phrase[i] == 0) {
       phrase[j] = temp;
       phrase[j] = phrase[k];
       phrase[k] = temp;

      }
  }
 }
cout << phrase << endl;
}

当我输入“Hello world”时,结果是“ePllo World”

最佳答案

-首先,您可以使用条件更改 if 语句,如果您在短语的第一个字符处循环并遇到空格。

-其次,你可以改变你的交换方式:

  phrase[i] = temp;
  phrase[i] = phrase[j];
  phrase[j] = temp;

用这个:

 temp = phrase[i];
 phrase[i] = phrase[j];
 phrase[j] = temp;

关于c++ - 在C++中交换短语中单词的前两个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58811945/

相关文章:

c++ - boost中的安全 bool 成语?

c++ - 如何将 XML 文件拆分为多个 XML,以便每个新文件仅包含原始文件中的一个文本节点?

c++ - 使用 cin.get()。无数次

c++ - 为什么operator->重载在VC2010中不起作用?

c++ - Corba IDL : default value for struct members

c++ - 使用 xerces for c++ 调用 getDocument 时出现段错误

c++ - 如何不使用虚拟继承?

c++ - GTKMM set_value_vfunc 函数是一个谎言吗?

c++ - Qt QGridLayout - 删除项目间距

c++ - 空 unordered_multiset 中的元素