我正在尝试构建一个程序,该程序从输入中解析字符数组,然后返回格式化后的格式,省略多余的空格。
#include <stdio.h>
# include <ctype.h>
/* count charecters in input; 1st version */
int main(void)
{
int ch, outp=0;
char str[1000], nstr[1000];
/* collect the data string */
while ((ch = getchar()) != EOF && outp < 1000){
str[outp] = ch;
outp++;
}
for (int j = 0; j < outp-1; j++){
printf("%c",str[j]);
}
printf("\n");
for (int q = 0; q < outp-1; q++)
{
if (isalpha(str[q]) && isspace(str[q+1])){
for(int i = 0; i < outp; i++){
if (isspace(str[i]) && isspace(i+1)){
continue;
}
nstr[i] = str[i];
}
}
}
printf("\n");
printf("Formated Text: ");
for (int i = 0; i < outp-1; i++){
printf("%c", nstr[i]);
}
//putchar("\n");c
// printf("1");
return 0;
}
这是我的代码。数组永远不会被完全解析,通常会省略结尾,出现奇数字符并且过去的尝试产生了一个未被完全解析的数组,为什么?这是“ C编程语言”的练习1-9。
a)在将字符从str
复制到nstr
时,需要使用附加的索引变量。做类似的事情-
for(int i = 0, j = 0; i < outp -1; i++){
if (isspace(str[i]) && isspace(i+1)){
continue;
}
nstr[j++] = str[i];
}
b)打印nstr
时,使用的是原始字符串str
的长度。由于已删除空格,因此nstr
的长度将小于str
的长度。
您现在需要查找nstr
的长度或在条件下使用i < strlen(nstr) -1
。