当字符串是数字时我不想返回任何内容 这是我的代码,
#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/