【问题标题】:Merge multiple input strings to sort alphabetically合并多个输入字符串以按字母顺序排序
【发布时间】:2014-04-14 22:04:19
【问题描述】:

帮助!这里我有一个程序,按字母顺序对输入字符串进行排序。问题是它单独对输入的字符串进行排序,但我需要将它们合并并排序在一起。我做错了什么?

  int main (void)
    {
       char repeat;
       do{
        char string[128], string1[128], temp;
        int n, i, j;
        cout<<"\nEnter symbols: "<<endl;
        gets(string);
        n = strlen(string);
        for (i=0; i<n-1; i++)
        {
            for (j=i+1; j<n; j++)
            {
                int  s = tolower(string[i]) - tolower(string[j]);
                if ( s == 0 )
                {   
                    s = string[i] - string[j];
                }

                if (s > 0)
                {
                    temp = string[i];
                    string[i] = string[j];
                    string[j] = temp;
                }
            }
        }
        cout<<"\nSorted alphabetically: "<<endl;
        printf("\n%s", string);
        printf("\n");

        cout<<"\nEnter more symbols: "<<endl;
        gets(string1);
        n = strlen(string1);
        for (i=0; i<n-1; i++)
        {
          for (j=i+1; j<n; j++)
          {
            int  s = tolower(string1[i]) - tolower(string1[j]);
            if ( s == 0 )
            {   
             s = string1[i] - string1[j];
            }
            if (s > 0)
            {
              temp = string1[i];
              string1[i] = string1[j];
              string1[j] = temp;
            }
          }
        }
     cout<<"\nSorted alphabetically: "<<endl;

下面的函数合并字符串,当它们都已经排序时

  strcat(string, string1); 
  printf(\n%s", string);
  printf("\n");
  cout << "To repeat press j" << endl;
  cin >> repeat;
  }
  while ( repeat == 'j' );
  system("Pause");
  return 0;
}

【问题讨论】:

  • 您要对字符串或字符进行排序吗?
  • chars - 形成用户输入,以便在第二次输入后新字母会与旧字母合并然后进行排序。

标签: string sorting merge


【解决方案1】:

最简单的方法是将字符串合并成一个新的。

int main (void)
    {
       char repeat;
       do{
        char string[128], string1[128],string2[256], temp;
        int n, i, j;
        cout<<"\nEnter symbols: "<<endl;
        gets(string);
        cout<<"\nEnter more symbols: "<<endl;
        gets(string1);
        strcpy (string2,string);
        strcat (string2,string1);
        // rest of your code here. You only need to sort string2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多