2016-03-02 113 views
0

我需要用以下帮助创建字符串数组:从输入字符串

独立大写的每个连续的阵列,小写字母和数字到从输入字符串单独字符串。假设输入字符串只包含大写,小写字母和数字。输入字符串没有空格。

Example: 
Input string: thisIS1inputSTRING 
OUTPUT: 
1. string: this 
2. string: IS 
3. string: 1 
4. string: input 
5. string: STRING 

下面的程序不给任何输出:

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

int main() { 
    char str[512], word[256]; 
    int i = 0, j = 0; 

    printf("Enter your input string:"); 
    gets(str); 

    while (str[i] != '\0') { 

     //how to separate strings (words) when changed from 
     //uppercase, lowercase or digit? 
     if (isdigit(str[i]) || isupper(str[i]) || islower(str[i])) { 
      word[j] = '\0'; 
      printf("%s\n", word); 
      j = 0; 
     } else { 
      word[j++] = str[i]; 
     } 
     i++; 
    } 

    word[j] = '\0'; 
    printf("%s\n", word); 

    return 0; 
} 
+2

'如果(ISDIGIT测试( str [i])|| isupper(str [i])|| islower(str [i]))将始终为真。因此,您将'word'的第一个字符设置为'\ 0'多次并打印多次。 –

+0

@Cool Guy设置(str [i] =='')if语句会将输入字符串中的单词与输入字符串中的空格分开。是否有可能只修改上述程序中的if语句,以便在每次大写,小写或数字更改之后进行分离? – user300048

+1

有必要检查变化的字符类型。 – BLUEPIXY

回答

2

您的解决方案就错了,因为也写在注释语句(isdigit(str[i]) || isupper(str[i]) || islower(str[i]))总是正确的。

如果您想使用if声明来坚持解决方案,那么您必须检查下一个字符。如果下一个字符类型与实际字符类型不同,则必须打印出您的单词,因为下一个字符是不同的类型。

我调整您的代码如下:

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

int main() { 
    char str[512], word[256]; 
    int i = 0, j = 0; 

    printf("Enter your input string:"); 
    gets(str); 

    while (str[i] != '\0') { 
      //how to separate strings (words) when changed from 

      // Is the next character the end of the string? 
      if(str[i+1] != '\0'){ // <<< 
       //uppercase, lowercase or digit? 
       if (
        isdigit(str[i]) && (isupper(str[i+1]) || islower(str[i+1])) // <<< 
        || isupper(str[i]) && (isdigit(str[i+1]) || islower(str[i+1])) // <<< 
        || islower(str[i]) && (isupper(str[i+1]) || isdigit(str[i+1])) // <<< 
       ){ 
         word[j] = str[i]; // <<< 
         word[j+1] = '\0'; // <<< 
         printf("%s\n", word); 
         j = 0; 
       } else { 
         word[j++] = str[i]; 
       } 
      } 
      else { 
       // End of the string, write last character in word 
       word[j] = str[i]; // <<< 
       word[j+1] = '\0'; // <<< 
       printf("%s\n", word); 
      } 
      i++; 
    } 
    return 0; 
} 

这将导致以下的输出:

Enter your input string:this 
IS 
1 
input 
STRING 

您可以通过自己的link[^]

+1

这不能正常工作,输出中缺少最后一个字符。 – Groo

+0

哦,我明白了,感谢您的建议,最后我不得不添加一行。我知道这不是很好的代码,但工作。 – Frodo