从输入字符串创建字符串数组

标签 c string

我需要以下方面的帮助:

将每个连续的大写字母、小写字母和数字数组从输入字符串中分离成单独的字符串。假设输入字符串只包含大写、小写字母和数字。输入字符串没有空格。

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

最佳答案

您的解决方案出错了,因为注释中也写了语句 (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[^]

关于从输入字符串创建字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746761/

相关文章:

c - c、fclose()、remove()、rename() 中的奇怪行为

c - 使用 scanf() 进行输入验证

c++ - 全局变量的顺序会改变 C++/OpenGL 中的性能

c - setsockopt() 错误 : Numerical argument out of domain

python - 将 NumPy 字符串数组映射为整数

regex - 使用正则表达式识别字母/数字组合并存储在字典中

无法在 dsPIC33F 上初始化 PWM

Java:比较具有不同顺序的关键字的字符串

java - 是否可以在 java 中搜索包含压缩对象的文件?

string - 递归删除子字符串的出现