使用字串概念來移除句子中空格的 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
廣告