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 - 为什么 printf 在调用后不会刷新,除非格式字符串中有换行符?

javascript - 将具有重复值的字符串数组转换为基于索引的对象数组

c# - 清理属性名称的字符串

java - 将字符串转换为标记

javascript - 如何从用户输入中拆分逗号分隔的字符串

c - 无法将文件中的字符串读取到数组中以最终进行排序

c - 为什么允许命名嵌套结构?

c - Linux block 设备驱动程序: how to handle REQ_DISCARD

arrays - 具有最大范围Excel VBA的列上的序号

javascript - 将新行动态添加到具有从 csv 文件创建的标题的数组中