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

โปรแกรม C ลบ n ตัวอักษรจากตำแหน่งที่กำหนดในสตริง

โจทย์

เขียนฟังก์ชันผู้ใช้เพื่อลบ N ตัวอักษรจากตำแหน่งที่กำหนดในสตริงที่ผู้ใช้ป้อนตอนรันไทม์

วิธีแก้

อัลกอริทึม

ขั้นตอน 1 - เริ่ม

ขั้นตอน 2 - อ่านสตริงตอนรันไทม์

ขั้นตอน 3 - อ่านตำแหน่งที่จะเริ่มลบ

ขั้นตอน 4 - อ่าน n จำนวนตัวอักษรที่จะลบ

ขั้นตอน 5 - เรียกฟังก์ชัน deletestr(str,p,n) ไปขั้นตอน 7

ขั้นตอน 6 - หยุด

ขั้นตอน 7 - ฟังก์ชัน deletestr(str,p,n)

1. for i =0 , j = 0 to Length[str]
2. do if i = p-1
3. i = i + n
4. str[j] = str[i]
5. str[j] = NULL
6. print str

ตัวอย่าง

โปรแกรม C ลบ n ตัวอักษรในสตริง:

#include <stdio.h> #include <conio.h> // prototype of function void del_str(char [],int, int); main(){    int n,p;    char str[30];    printf("\n Enter the String:");    gets(str);    fflush(stdin);    printf("\n Enter the position from where the characters are to be deleted:");    scanf("%d",&p);    printf("\n Enter Number of characters to be deleted:");    scanf("%d",&n);    del_str(str,p,n); } //function call void del_str(char str[],int p, int n){    int i,j;    for(i=0,j=0;str[i]!='\0';i++,j++){       if(i==(p-1)){          i=i+n;       }       str[j]=str[i];    }    str[j]='\0';    puts(" The string after deletion of characters:");    puts(str); }

ผลลัพธ์

Enter the String:Tutorials Point C programming Enter the position from where the characters are to be deleted:10 Enter Number of characters to be deleted:6 The string after deletion of characters: Tutorials C programming