[英]I want to split a string into two strings in C
我想用逗號分割一個字符串,並將字符串中的第一個數字分隔成它自己的新字符串,即我想保持在一起的字符串的 rest。
到目前為止,我已經通過使用strtok()
進行了嘗試,並且可以將第一個數字放入它自己的字符串中,但是現在我不知道如何將字符串的 rest 保持在一起。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr;
char *restOfstr;
int n;
//This is wrong, I know, but I want to populate
//the rest of the string after the first comma
//into a single string without the UID.
uidStr = strtok(testStr, ",");
while (n < 5)
{
restOfstr = strtok(NULL, ",");
n++;
}
return 0;
}
您可以使用strchr
查找字符串中的第一個逗號。
然后使用strncpy
獲取字符串中的數字。
完整代碼:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *str = "1000,first,second,third,+abc";
char *s = strchr(str, ',');
if(!s)
return -1;
char num[10];
strncpy(num, str, s-str);
num[s-str] = '\0';
int a = strtol(num, NULL, 10);
printf("num = %d\nthe remaining: %s\n", a, s+1);
return 0;
}
strtok
工作正常,您必須記住,它返回一個指向每個標記化單詞的指針,因此您需要兩個指針,一個用於第一個標記,另一個用於字符串的 rest。
#include <stdio.h>
#include <string.h>
int main()
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr; //pointer to uid
char *restOfstr; //pointers to the rest of the string
uidStr = strtok(testStr, ","); //uid remains in testStr
restOfstr = strtok(NULL, "\n"); //rest of the string
puts(uidStr); //or puts(testStr) to print uid
puts(restOfstr); //print rest of the string
return 0;
}
如果您想要更安全的 function 可以使用strtok_s
。
#include <string.h>
#include <stdio.h>
int main(int ac, char **av) {
while (--ac) {
char *p = *++av;
char *t = strtok(p, ",");
char *r = strtok(NULL,"");
printf("%s : %s\n", t, r);
}
return 0;
}
注意傳遞給第二個strtok的空字符串“”表示找不到分隔符,因此返回字符串的rest。
除了@mevets 和@anastaciu 提供的出色答案(我會用這些回答 go),這段代碼也可以正常工作。
#include <string.h>
#include <stdio.h>
int main(int argc, char** argv) {
char _p[] = "1000,Hey,There";
char* str1 = strtok(_p, ",");
char* str2 = strtok(NULL, "");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.