2013-10-15 194 views
1

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

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

你发现了什么问题? – SJuan76

+0

你是否是正则表达式的粉丝,想不出其他的东西? – P0W

回答

1

这里有两个问题:

  1. strtok的第二个参数应该是你想要的分隔符只有字符串,明确。就你而言,我认为这只是一个空间(" ")。
  2. scanf中的%s在输入上看到空格时停止读取。

修改程序:

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

如果你想允许首字母大写的名称为好,然后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; 
} 
+0

用户输入他们的名字,或者结合(AlexTank)或者分开(Alex Tank),当通过 – ArcticBlueAlex

+0

@ArcticBlueAlex读取大写字母时,字符串应该被分割(插入一个空格)对不起,我没有理解这个意思你的问题。我更新了我的答案。 – lurker

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

看看这对你的作品!