我在这里写了一段代码,不使用 strtok() 函数将给定句子中的单词分开。但问题是它只打印第一个单词。为什么其余单词不打印?
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This, a sample string.";
int i=0,k,begin,end;
while(str[i]!='\0'){
while(str[i]==' '){
i++;
}
begin = i;
while(str[i]!=' ' && str[i]!='\0'){
i++;
}
end = i-1;
char *ptr =(char *)malloc((end-begin)*sizeof(char));
for(k=begin;k<=end;k++){
ptr[k] = str[k];
}
printf("%s\n",ptr);
if(str[i]=='\0'){
break;
}
}
}
最佳答案
完整的代码应该是这样的
我已经在您的代码之上更改了代码。
int main ()
{
char str[] ="This, a sample string.";
int i=0,k,begin,end;
int t;
while(str[i]!='\0'){
begin = i;
while(str[i]!=' ' && str[i]!='\0'){
i++;
}
end = i-1;
char *ptr = (char *) malloc( (i-begin)*sizeof(char) + 1);
t=0;
for(k=begin;k<=end;k++){
ptr[t++] = str[k];
}
ptr[t] = '\0';
puts(ptr);
if(str[i]=='\0'){
break;
} else
while(str[i] == ' ') i++; //To avoid multiple spaces
}
return 0;
}
-谢谢
关于c - 没有库函数将单词从句子中分离出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40147794/