[英]How to split the a string into separate words in C, where the space is not constant?
[英]How can I separate a String into separate items (separated by space) with C
抱歉,我不確定如何正確表達我遇到的問題。 我正在接受用戶輸入的無符號字符,假設unsigned char array = "123 343 342 4235 87 34 398"
,現在我希望將字符串中的每個數字除以空格,再分成一個單獨的數組
items[0] = 123
items[1] = 343
items[2] = 342
等等。 我該如何處理?
我忘了提到我正在使用Linux進行編譯,因此tutorialspoint.com/c_standard_library/c_function_strtok.htm
不為我編譯或工作
這確實是一個常見的問題,例如在這里: 用C標記字符串
但是無論如何,這是一個答案:
#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]);
}
}
編輯:此代碼在輸入為非空且不包含定界符的極端情況下失敗。 如果第一次調用strtok()返回NULL,則應檢查該條件。
您想與stroik結合使用atoi來檢索整數
我從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.