此处的此代码用于反转字符串中的字。问题是它只能反转字符串中的第一个单词。当我跑过踪迹时,发现它在遇到语句后停止了。if(s[indexCount] == '\0') break;
字符串中的反转字
为什么每当第一个单词逆转时,即使其他字符出现在第一个单词后面,代码也会变为空字符。
#include <iostream>
using namespace std;
int main()
{
string s;
char tchar;
int indexCount=0,charCount=0,wordIndex;
cin>>s;
while(1){
if(s[indexCount]==' ' && charCount==0) continue;
if(s[indexCount]==' ' || s[indexCount]=='\0'){
wordIndex=indexCount-charCount;
charCount=indexCount-1;
while(charCount!=wordIndex && charCount>wordIndex){
tchar=s[wordIndex];
s[wordIndex]=s[charCount];
s[charCount]=tchar;
charCount--;
wordIndex++;
}
if(s[indexCount] == '\0') break;
indexCount++; charCount=0;
}
else{
charCount++;
indexCount++;
}
}
cout<<"\nReveresed words in the string : \n\t"<<s<<endl;
return 0;
}
另外我使用的是while(1)
。它是否使这是一个错误的代码?
您可能想要将其更改为'while(true)'。我不会说它是“坏”,但如果可以的话,你应该在“while”条款中加入一个明确的条件。这样,当你看到循环时,它说明了循环操作的条件。 –
对于哪些输入您收到不良结果? – fghj
反转整个字符串和反转字符串中的单词有什么区别? –