c/c++语言开发共享如何解析用逗号分隔的字符串?

Char *strings = "1,5,95,255" 

我想将每个数字存储到一个int变量中,然后将其打印出来。

例如,输出变为这样。

值1 = 1

value2 = 5

Value3 = 95

value4 = 255

我想在循环中执行此操作,因此如果我在字符串中有超过4个值,我应该能够获得其余的值。

我想看看这个例子。 我知道这对你们很多人来说非常基础,但我发现它有点挑战性。

谢谢

    从cplusplus strtok示例修改:

     #include  #include  int main () { char str[] ="1,2,3,4,5"; char *pt; pt = strtok (str,","); while (pt != NULL) { int a = atoi(pt); printf("%dn", a); pt = strtok (NULL, ","); } return 0; } 

    我不知道上面评论中提到的function,但是按照你要求的方式做你想做的事我会尝试这个或类似的东西。

     char *strings = "1,5,95,255"; char number; int i = 0; int value = 1; printf ("value%d = ", value); value++; while (strings[i] != NULL) { number = string[i]; i++; if (number == ',') printf("nvalue%d = ",value++); else printf("%s",&number); } 

    如果你没有可修改的字符串,我会使用strchr 。 搜索下一个,然后像那样扫描

    需要了解更多c/c++开发分享如何解析用逗号分隔的字符串?,也可以关注C/ C++技术分享栏目—计算机技术网(www.ctvol.com)!

     #define MAX_LENGTH_OF_NUMBER 9 char *string = "1,5,95,255"; char *comma; char *position; // number has 9 digits plus  char number[MAX_LENGTH_OF_NUMBER + 1]; comma = strchr (string, ','); position = string; while (comma) { int i = 0; while (position < comma && i <= MAX_LENGTH_OF_NUMBER) { number[i] = *position; i++; position++; } // Add a NULL to the end of the string number[i] = ''; printf("Value is %dn", atoi (number)); // Position is now the comma, skip it past position++; comma = strchr (position, ','); } // Now there's no more commas in the string so the final value is simply the rest of the string printf("Value is %dn", atoi (position)l 

      以上就是c/c++开发分享如何解析用逗号分隔的字符串?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/979909.html

      (0)
      上一篇 2021年12月13日
      下一篇 2021年12月13日

      精彩推荐