如何让 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/