c - 当字符串为数字时C语言

标签 c char

当字符串是数字时我不想返回任何内容 这是我的代码,

#include <string.h>
#include <ctype.h>
int num = 0;

char* findWord(char* subString) {
        char* word = malloc(sizeof(char) * (strlen(subString) + 1));
        int i = 0;
        int Position = 0;
        num = 0;


        while (ispunct(subString[i]) != 0 || isspace(subString[i]) != 0) {
                i++;
        }
        num = i;

        while (ispunct(subString[i]) == 0 && isspace(subString[i]) == 0) {
                word[Position] = subString[i];
                i++;
                Position++;
        }

        word[Position] = '\0';
        return word;
}

char** wordList(const char* s) {
        int len = strlen(s);
        int i = 0;
        char* Copyword = malloc(sizeof(char) * len);
        strncpy(Copyword, s, len);
        char** result = (char**) malloc(sizeof(char*) * (len + 1));    
        char* word = NULL;

        word = findWord(Copyword);
        char* wordEnd = Copyword;

        while (*word != 0) {
                result[i] = word;              
                wordEnd = wordEnd + strlen(word) + num;
                word = findWord(wordEnd);              
                i++;
        }
        result[i] = '\0';
        free(Copyword);
        return result;
}

int main(void) {
        char** words = wordList("1 23 456 789");
        int i = 0;
        while (words[i] != NULL) {
                printf("%s\n", words[i]);
                free(words[i]); // We're done with that word
                i++;
        }
        free(words); // We're done with the list
        return 0;
 }

当字符串是句子时,我的代码没问题。 但是,在这种情况下,当字符串是数字时,我想不打印任何内容(就像空格一样)。 但我要做的是

1
23
456
789

我希望得到

nothing shows here! just a space

最佳答案

对于初学者:您将一个非 0 终止的 C-“字符串”(Copyword)传递给 findWord() 并在其中调用strlen() 就可以了。这不会因为运气不好而导致您的应用程序崩溃。

关于c - 当字符串为数字时C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32412296/

相关文章:

c - 将动态数组发送到函数 C++

java - 来自 logcat 调试的致命信号 11 (SIGSEGV) 位于 0x00000000(代码=1)

C 中 char 到 int 的结构体值

将字符串从一个指针复制到另一个指针

ios - Obj C 调用 Cocos2dx C++ 非静态函数

c - 我试图使用 for 循环找到素数 1-n

c - 在 C 中,如何将 char* 转换为 hex

c - 在C中将char *插入二叉搜索树

ios - 没有得到 String 中 char 的正确索引

c++ - 在 Arduino 中转换为字符的字符串