编写用户函数以从给定字符串中的位置删除 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> // 函数原型 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); } //函数调用 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(" 删除字符后的字符串:"); puts(str); }输出结果
执行上述程序时,会产生以下结果 -
Enter the String:nhooo.com C programming Enter the position from where the characters are to be deleted:10 Enter Number of characters to be deleted:6 删除字符后的字符串: Tutorials C programming