简体   繁体   English

如何使用C将字符串分成单独的项目(按空格分隔)

[英]How can I separate a String into separate items (separated by space) with C

Sorry I'm not sure how to correctly word the problem I'm having. 抱歉,我不确定如何正确表达我遇到的问题。 I'm taking the user's input which is unsigned char, let's say unsigned char array = "123 343 342 4235 87 34 398" and now I would like to have each number in that String divided by the space into a separate array 我正在接受用户输入的无符号字符,假设unsigned char array = "123 343 342 4235 87 34 398" ,现在我希望将字符串中的每个数字除以空格,再分成一个单独的数组

items[0] = 123 items[1] = 343 items[2] = 342 items[0] = 123 items[1] = 343 items[2] = 342

and so forth. 等等。 How can I approach this? 我该如何处理?

I forgot to mention I'm compiling with Linux so tutorialspoint.com/c_standard_library/c_function_strtok.htm 我忘了提到我正在使用Linux进行编译,因此tutorialspoint.com/c_standard_library/c_function_strtok.htm

Does not compile for me or work 不为我编译或工作

this is indeed a common question, for example here: Tokenizing strings in C 这确实是一个常见的问题,例如在这里: 用C标记字符串

but anyways, here is one answer: 但是无论如何,这是一个答案:

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

int main(void) {
    const int maxParsed = 32;
    char array[] = "123 343 342 4235 87 34 398";

    char* parsed[maxParsed];
    char* token = strtok(array, " ");

    int numParsed = 0;
    int i;

    while(token) {
        parsed[numParsed] = token;
        token = strtok(NULL, " ");
        numParsed++;
        if(numParsed == maxParsed) { break; }
    }


    for(i=0; i<numParsed; i++) {
        printf("parsed string %d: %s \n", i, parsed[i]);
    }
}

EDIT: This code fails in the edge case where the input is non-empty and contains no delimiters. 编辑:此代码在输入为非空且不包含定界符的极端情况下失败。 You should check for that condition if the first call to strtok() returns NULL. 如果第一次调用strtok()返回NULL,则应检查该条件。

You want to use strtok in combinaison with atoi for retrieving integers 您想与stroik结合使用atoi来检索整数

I adapted the library example from tutorialpoints. 我从tutorialpoints改编了库示例

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

int main()
{
   const char str[27] = "123 343 342 4235 87 34 398";
   const char s[2] = " "; //Your delimiter, here a singlespace
   char *token;

  /* get the first token */
  token = strtok(str, s);

  /* walk through other tokens */
  while( token != NULL ) 
  {
      printf( " %d\n", atoi(token) ); // atoi converting char* to int !

      token = strtok(NULL, s);
  }

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM