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