gpt4 book ai didi

c - 从c中的字符串中删除前导空格

转载 作者:行者123 更新时间:2023-11-30 20:08:15 26 4
gpt4 key购买 nike

我正在逐个字符地读取字符串,然后对于找到的每个单词(用空格分隔)计算每个单词的长度,最后将所有信息打印到屏幕上。

示例运行:更难掌握

    n=8, s=[trickier]
n=2, s=[to]
n=6, s=[master]
n=0, s=[]
n=-1, s=[]

这是正确的,我得到的是:

    n=0, s=[]
n=0, s=[]
n=8, s=[trickier]
n=2, s=[to]
n=0, s=[]
n=6, s=[master]
n=0, s=[]
n=-1, s=[]

问题是字符串中的前导空格我已经查看了很多有关如何修剪前导空格的示例,但我无法获得任何与当前源代码一起使用的内容。

代码:

#include "getword.h"

int getword(char *w) {
int iochar;
int index = 0;
int numberofchars = 0;

if (numberofchars == 0 && iochar == '\n') {
w[index] = '\0';
iochar = EOF;
return 0;
}
if (iochar == EOF && numberofchars == 0) {
w[index] = '\0';
return -1;
}

while ((iochar = getchar()) != EOF) {
if (iochar != ' ' && iochar != '\n') {
w[index] = iochar;
index++;
numberofchars++;
} else {
w[index] = '\0';
if (strcmp(w, "done") == 0) {
return -1;
} else {
return numberofchars;
}
}
} //after while loop
} // end of function

int main() {
int c;
char s[STORAGE];

for (;;) {
(void)printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1)
break;
}
}

最佳答案

代码太复杂了,一些无用且虚假的测试会产生未定义的行为:

  • 在使用 getchar() 读取之前,在 getword() 中测试 iochar 是没有意义的。
  • 在单个 printf() 调用中结合读取、测试和写入单词也是错误的:您应该读取,然后测试,如果未完成则输出。

这是一个简化版本:

#include <stdio.h>
#include <string.h>

#define STORAGE 50

// read a word into an array of size `size`.
// return the number of characters read.
int getword(char *w, size_t size) {
int c;
size_t i = 0;

while (i + 1 < size && (c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n') {
if (i == 0)
continue; // ignore leading spaces
else
break; // stop on white space following the word.
}
w[i++] = c;
}
w[i] = '\0';
return i;
}

int main() {
char s[STORAGE];
int len;

while ((len = getword(s, sizeof s)) != 0) {
if (!strcmp(s, "done"))
break;
printf("n=%d, s=[%s]\n", len, s);
}
return 0;
}

关于c - 从c中的字符串中删除前导空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57744334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com