使用字符串概念来移除句子中空格的 C 程序。
问题
在运行时,通过检查字符的每个索引处的空格来使用 while 循环从输入的字符串中移除所有空格。
解决办法
考虑以下给出的示例 −
它从给定的字符串中移除了所有空格。给定的字符串是教程点 C 编程。移除空格后的结果是教程点 C 编程。
字符数组称为字符串。
以下给出了字符串的声明 −
char stringname [size];
例如,char string[50]; 长度为 50 个字符的字符串。
初始化
- 使用单个字符常量。
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字符串常量。
char string[10] = “Hello”:;
访问
有一个控制字符串“%s”,用于访问字符串,直到它遇到 '\0'。
我们用于移除字符串之间空格的逻辑如下 −
while(string[i]!='\0'){
check=0;
if(string[i]==' '){
j=i;
while(string[j-1]!='\0'){
string[j] = string[j+1];
j++;
}
check = 1;
}
if(check==0)
i++;
}示例
以下是 C 程序,用于通过使用字符串概念来移除句子中的所有空格 −
#include<stdio.h>
int main() {
char string[50];
int i=0, j, check;
printf("Enter any statement: ");
gets(string);
while(string[i]!='\0') {
check=0;
if(string[i]==' ') {
j=i;
while(string[j-1]!='\0') {
string[j] = string[j+1];
j++;
}
check = 1;
}
if(check==0)
i++;
}
printf("
Sentence without spaces: %s", string);
getch();
return 0;
}输出
当执行以上程序时,它会生成以下输出 −
Run 1: Enter any statement: Tutorials Point C Programming Sentence without spaces: TutorialsPointCProgramming Run 2: Enter any statement: Welcome to the world of tutorials Sentence without spaces: Welcometotheworldoftutorials
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP