好的,所以这段代码几乎可以工作,只是它弄乱了每一行的末尾。 例如,如果我有一个包含以下三行的文本文件作为我的标准输入:
This is a test
For you to see
How this code messes up
输出读取:
siht si a
tsetroF uoy ot
eeswoH siht edoc sessem
pu
如果你发现了什么,请告诉我 谢谢
void reverse(char *beg, char *end)
{
while (beg<end)
{
char temp = *beg;
*beg++ = *end;
*end-- = temp;
}
}
void reverseWords(char *str)
{
char *beg = NULL;
char *temp = str;
while (*temp)
{
if ((beg == NULL) && (*temp != ' '))
{
beg = temp;
}
if (beg && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0')))
{
reverse(beg, temp);
beg = NULL;
}
temp++;
}
}
最佳答案
不考虑代码中的新行。
在下面的代码中,我将所有出现的 *something == ' '
更改为调用新添加的方法 isWhiteSpace
,如果被检查的字符是空格、制表符、换行符或回车符:
void reverse(char *beg, char *end)
{
while (beg<end)
{
char temp = *beg;
*beg++ = *end;
*end-- = temp;
}
}
int isWhiteSpace(char value)
{
return value == ' ' || value == '\t' || value == '\r' || value == '\n';
}
void reverseWords(char *str)
{
char *beg = NULL;
char *temp = str;
while (*temp)
{
if ((beg == NULL) && !isWhiteSpace(*temp))
{
beg = temp;
}
if (beg && (isWhiteSpace(*(temp + 1)) || (*(temp + 1) == '\0')))
{
reverse(beg, temp);
beg = NULL;
}
temp++;
}
}
关于c - 使用 C 反转字符串中的每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261936/