[英]Reverse each word in a string using C
好的,所以這段代碼幾乎可以用了,只是弄亂了每一行的末尾。 例如,如果我的文本文件包含以下三行內容:
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
,如果要檢查的字符是空格,制表符,換行符或回車符,則返回true返回字符:
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++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.