c - 使用 C 反转字符串中的每个单词

标签 c arrays string char reverse

好的,所以这段代码几乎可以工作,只是它弄乱了每一行的末尾。 例如,如果我有一个包含以下三行的文本文件作为我的标准输入:

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/

相关文章:

c# - 如何在 C# 互操作调用中从 C# 实例化数组中的 C 取回数据?

c - c中的字符串指针和字符数组

java - 如何打印我的 Java 对象而不得到 "SomeType@2f92e0f4"?

python - 获取影响原始数组的 2D numpy 数组的对角线

c - 使用函数反转 C 中的字符串

Python subprocess.communicate() 不捕获简单二进制文件的输出

c - Kernighan/Ritchie 的第 5.10 节命令行参数/可选参数

c - 如何从 C 调用 Clojure 函数?

c - pthread_create() 的返回码是 11

javascript - 如何通过在 Javascript 中使用两个普通数组来创建具有相同键的关联数组