C程序从字符串中删除空格,空格
2021-07-07 09:11:51
深夜i
--
--
C
程
序
从
字
符
串
中
删
除
空
格
,
空
格
从字符串中删除空格或多余空格的 C 程序,例如,考虑字符串
"C programming"
这个字符串中有两个空格,所以我们的程序会打印字符串“C编程”。 当空格在任何地方连续出现超过一次时,它将删除空格。
C程序
#include <stdio.h>
int main()
{
char text[1000], blank[1000];
int c = 0, d = 0;
printf("Enter some text\n");
gets(text);
while (text[c] != '\0') {
if (text[c] == ' ') {
int temp = c + 1;
if (text[temp] != '\0') {
while (text[temp] == ' ' && text[temp] != '\0') {
if (text[temp] == ' ') {
c++;
}
temp++;
}
}
}
blank[d] = text[c];
c++;
d++;
}
blank[d] = '\0';
printf("Text after removing blanks\n%s\n", blank);
return 0;
}
如果需要,您可以将空白复制到文本字符串中,以便修改原始字符串。
下载删除空格程序。
程序输出:
使用指针的 C 编程代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SPACE ' '
char *process(char*);
int main()
{
char text[1000], *r;
printf("Enter a string\n");
gets(text);
r = process(text);
printf("\"%s\"\n", r);
free(r);
return 0;
}
char *process(char *text) {
int length, c, d;
char *start;
c = d = 0;
length = strlen(text);
start = (char*)malloc(length+1);
if (start == NULL)
exit(EXIT_FAILURE);
while (*(text+c) != '\0') {
if (*(text+c) == ' ') {
int temp = c + 1;
if (*(text+temp) != '\0') {
while (*(text+temp) == ' ' && *(text+temp) != '\0') {
if (*(text+temp) == ' ') {
c++;
}
temp++;
}
}
}
*(start+d) = *(text+c);
c++;
d++;
}
*(start+d)= '\0';
return start;
}
上一篇:
idea打包java可执行jar包
下一篇:
改变字符串大小写的C程序
评论区