用C分割字符串

时间:2013-10-15 19:28:14

标签: c string split

程序基本上应该将名称拆分为F和L名称。用户将他们的名字放入组合或空格中(例如AlexTank或Alex Tank)。程序应该读入每个大写字母并用空格分割字符串。我遇到的问题是我的程序拆分名称(识别大写字母)但从字符串的新输出中排除大写字母。

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

int main()
{
    char name[50], first[25], last[25];
    char *pch;
    char* key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    // ask user for name
    printf("What is your name? ");
    scanf("%s", name);

    printf("Hello \"%s\" here is your First and Last Name:\n", name);
    pch = strtok(name, key);
    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, key );
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

有两个问题:

  1. strtok的第二个参数应该只是您想要的分隔符字符串。在您的情况下,我认为这只是一个空格(" ")。
  2. %s中的scanf会在看到输入的空格时停止阅读。
  3. 修改后的程序:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char name[50], first[25], last[25];
        char *pch;
    
        // ask user for name
        printf("What is your name? ");
        //scanf("%s", name);
        fgets(name, 50, stdin);
    
        printf("Hello \"%s\" here is your First and Last Name:\n", name);
        pch = strtok(name, " ");
        while (pch != NULL)
        {
            printf("%s\n", pch);
            pch = strtok(NULL, " ");
        }
        return 0;
    }
    

    如果您也想允许CamelCase名称,那么strtok将无法自行运行,因为它会破坏分隔符。您可以执行一些简单的操作,例如预处理名称和插入空格,或编写自定义标记生成器。这是插入空间构思方法。如果您只是插入空格,那么strtok将执行您想要的操作:

    #include <stdio.h>
    #include <string.h>
    
    void insert_spaces(char *in, char *out)
    {
        if ( !in || !out )
            return;
    
        while ( *in )
        {
            if (isupper(*in))
                *out++ = ' ';
    
            *out++ = *in++;
        }
    
        *out = '\0';
    }
    
    int main()
    {
        char in_name[50], first[25], last[25];
        char name[100];
        char *pch;
    
        // ask user for name
        printf("What is your name? ");
        //scanf("%s", name);
        gets(in_name);
    
        printf("Hello \"%s\" here is your First and Last Name:\n", in_name);
    
        insert_spaces(in_name, name);
    
        pch = strtok(name, " ");
    
        while (pch != NULL)
        {
            printf("%s\n", pch);
            pch = strtok(NULL, " ");
        }
        return 0;
    }
    

答案 1 :(得分:0)

strtok假设您不希望返回分隔符 - 因此它将使用它们并返回“其余”(即仅限小写字母)。我建议一个更简单的方法:一次回输输入字符串一个字符;如果您看到一个大写字母,但不只是看到一个空格,请将其添加进去。它看起来像这样:

#include <stdio.h>

int main()
{
    char name[50];

    // ask user for name
    printf("What is your name? ");
    //scanf("%s", name);
    fgets(name, 49, stdin);

    printf("Hello. Your name is ");
    int ii = 1, foundSpace = 0;
    printf("%c", name[0]);
    while (name[ii] != '\0')
    {
        if (name[ii]==' ') foundSpace = 1;
        if (foundSpace == 0 && isupper(name[ii])) {
          printf(" %c", name[ii]);
        }
        else {
          putchar(name[ii]);
          foundSpace = 0;
        }
        ii++;
    }
    return 0;
}

看看这是否适合你!