反转字符串中的单词 [英] Reversing words within a string

查看:56
本文介绍了反转字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要反转字符串中的单词.我觉得我正朝着正确的方向前进.但我一直得到不稳定的输出,不禁认为这与我的 strncat() 函数有关.你们中的任何人是否看到任何问题,我已经决定处理它.我愿意接受其他方法的建议.

I am to reverse the words within a string. I feel like I'm headed in the right direction. But I keep getting wonky output and cant help but think it has to do with my strncat() function. Do any of you see any issues with out I've decided to handle it. I'm open to suggestion on other ways to do it.

int main()
{
  int ch, ss=0, s=0;
  char x[3];
  char *word, string1[100], string2[100], temp[100];
  x[0]='y';

  while(x[0]=='y'||x[0]=='Y')
  {
    printf("Enter a String: ");
    fgets(string1, 100, stdin);
    if (string1[98] != '\n' && string1[99] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }

    word = strtok(string1, " ");

    while(word != NULL)
    {
      s = strlen(word);
      ss=ss+s;

      strncpy(string2, word, s);
      strncat(string2, temp, ss);
      strncpy(temp, string2, ss);

      printf("string2: %s\n",string2);
      printf("temp: %s\n",temp);      
      word = strtok(NULL, " ");
    }

    printf("Run Again?(y/n):");
    fgets(x, 2, stdin);
    while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
  }

  return 0;
}

这是我的输出:

Enter a String: AAA BBB CCC DDD EEE

string2: AAA
temp: AAA

string2: BBBAAA
temp: BBBAAA

string2: CCCAAABBBAAA
temp: CCCAAABBB

string2: DDDAAABBBAAACCCAAABBB
temp: DDDAAABBBAAA

string2: EEE
AABBBAAACCCAAABBBDDDAAABBBAAA
temp: EEE
AABBBAAACCCA

推荐答案

你需要初始化至少"strcat()参数的第一个字节,因为它期望它的参数以 nul 终止,所以

You need to initialize "at least" the first byte of strcat() parameters, because it expects it's parameters to be nul terminated, so

string2[0] = '\0';

会有所帮助,但您第一次不需要 strcat(),您可以使用 strcpy() 代替.

would help, but you don't need strcat() for the first time, you can use strcpy() instead.

这篇关于反转字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆