分组字符串数组C.

我已经创建了一个字符串数组,我正在尝试将字符串数组分组.

到目前为止我的代码看起来像这样:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char *argv[]) {
    char *results[] = {"Canada", "Cycling", "Canada", "Swimming", "India", "Swimming", "New Mexico",
                       "Cycling", "New Mexico", "Cycling", "New Mecico", "Swimming"};



    int nelements, i, country_count;

    nelements = sizeof(results) / sizeof(results[0]);

    for (i = 0 ; i < nelements; i++) {
        printf("%s\n", results[i]);
    }

    return 0;
}

打印出来的是:

Canada
Cycling
Canada
Swimming
India
Swimming
New Mexico
Cycling
New Mexico
Cycling
New Mexico
Swimming

但是我想把各个国家的运动和各自的计数分组,我希望看起来像这样:

Canada
    Cycling  1
    Swimming 1

India
    Swimming 1

New Mexico
    Cycling  2
    Swimming 1

我正在考虑使用数组中的每个i 2元素对国家进行分类,并使用strcmp删除重复的国家/地区字符串,但我不确定如何使用每个国家/地区的运动计数来执行此操作.

我只是不确定如何解决这个问题.任何形式的帮助将不胜感激.

最佳答案
鉴于你的数组,我可以看到国家名称可供选择.如果这是格式数据可用,您可以按照以下代码.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
   char *results[] = {"Canada", "Cycling", "Canada", "Swimming", "India","Swimming", "New Mexico",
               "Cycling", "New Mexico", "Cycling", "New Mexico", "Swimming"};



   int nelements, i, sport_count=0,country_change =0;
   char country[50];char sport[50];
   strcpy(country,results[0]);
   printf("%s\n", country);
   strcpy(sport,results[1]);
   nelements = sizeof(results) / sizeof(results[0]);

   for (i = 1 ; i < nelements; i++) 
   {
      if(((i%2)==0) && (strcmp(country,results[i])))
      {
         //sport_count++;
         printf("\t%s %d\n", sport,sport_count);
         country_change =1;
         strcpy(country,results[i]);
         printf("%s\n", country);
      }
      else if((i%2)==1)
      {
          if(country_change)
          {
             strcpy(sport,results[i]);
             country_change = 0;
             sport_count = 0;
          }

          if(!strcmp(sport,results[i]))
          {
              sport_count++;
          }
          else
          {
              printf("\t%s %d\n", sport,sport_count);
              strcpy(sport,results[i]);
              sport_count = 1;
          }
             //strcpy(country,results[i]);
       }

    }
    printf("\t%s %d\n", sport,sport_count);

 return 0;
}

基本上这就是我在这里要做的:

>将第一个索引存储在变量中.
>在每个偶数迭代中检查国家名称是否等于存储的名称.如果没有更新名称.
>在每个奇数迭代中,您只需打印出名称即可.
>运动名称存储在变量中,int变量sports_count保存计数.
>如果新国家到达,则首先打印运动名称,而不是以运动名称和相关变量进行强制更新.
>最后的运动名称在循环外打印.

Output

Canada
        Cycling 1
        Swimming 1
India
        Swimming 1
New Mexico
        Cycling 2
        Swimming 1

转载注明原文:分组字符串数组C. - 代码日志