Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C ลบช่องว่างทั้งหมดในประโยคด้วยสตริง

ปัญหา

ลบช่องว่างทั้งหมดจากสตริงที่ป้อนขณะรัน โดยใช้ while loop ตรวจสอบช่องว่างที่แต่ละดัชนี

วิธีแก้ปัญหา

ตัวอย่าง: Tutorials Point C Programming → TutorialsPointCProgramming

การประกาศ สตริง

char stringname[size];

การเริ่มต้น

  • ค่าคงที่ตัวอักษรเดี่ยว
    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++;
}

ตัวอย่างโค้ด

#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("\nSentence 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