C語言程式:刪除給定字串中的n個字元
問題
編寫使用者函式,從給定字串的指定位置刪除N個字元。字串由使用者在執行時輸入。
解決方案
刪除給定字串中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
示例
以下是刪除給定字串中n個字元的C語言程式:
#include <stdio.h>
#include <conio.h>
// prototype of function
void del_str(char [],int, int);
main(){
int n,p;
char str[30];
printf("
Enter the String:");
gets(str);
fflush(stdin);
printf("
Enter the position from where the characters are to be deleted:");
scanf("%d",&p);
printf("
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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP