也许这属于代码检查站点?
您的方法对我来说似乎非常有效(除了我只调用一次strlen(words)并将结果保存在寄存器中)。
两个可能的错误如下所示:
wordend = strlen(words);
应该
wordend = strlen(words)-1;
和
for(j = wordstart ; j <= (wordend - wordstart) / 2 ; ++j) {
应该
for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
最终代码看起来像(带有一些额外的{}):
#include <stdio.h> int main(int argc,char *argv[]) { int i,j; char words[]= "this is a test"; int L=strlen(words); // Reverse each word for(i = 0; i < L; ++i) { int wordstart = -1; int wordend = -1; if(words[i] != ' '){ wordstart = i; for(j = wordstart; j < L; ++j) { if(words[j] == ' ') { wordend = j - 1; break; } } if(wordend == -1) wordend = L-1; for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) { char temp = words[j]; words[j] = words[wordend - (j - wordstart)]; words[wordend - (j - wordstart)] = temp; } i = wordend; } } printf("reversed string is %s:",words); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)