我想用C语言将一个字符串分割成两个字符串。

问题描述 投票:0回答:1

我想用逗号分割一个字符串,并将字符串中的第一个数字分离成自己的新字符串,其余的字符串我想保持在一起。

到目前为止,我已经尝试过使用 strtok() 我可以将第一个数字放入自己的字符串中,但现在我不知道如何将字符串的其余部分保持在一起。

#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;
}
c string loops split strtok
1个回答
1
投票

strtok 这个方法很好用,但你必须记住,它将返回一个指向每个标记字的指针,所以你需要两个指针,一个指向第一个标记,另一个指向字符串的其余部分。

演示

#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;
}

如果你想要更安全的功能,你可以使用 strtok_s.


1
投票

您可以使用 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;
}

1
投票

除了 @mevets 和 @anastaciu 提供的出色答案之外(我会选择这些),这段代码也能正常工作。

#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;
}

0
投票
#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的空字符串""意味着它找不到定界符,因此返回字符串的其余部分。

© www.soinside.com 2019 - 2024. All rights reserved.