1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 删除字符串中指定位置的字符

删除字符串中指定位置的字符

时间:2024-03-10 10:07:19

相关推荐

删除字符串中指定位置的字符

比如说删除字符串certainly中的第5个字符i,变成certanly。

具体实现如下:

首先:主函数框架如下:

#include <stdio.h>#include <windows.h>#include <conio.h>#define N 20void proc(char a[], char b[], int n);void main(){char str1[N], str2[N];int n;system("CLS");printf("Enter the string !\n");gets(str1);printf("Enter the position of the string deleted !\n");scanf("%d",&n);proc(str1,str2,n);printf("The new string is :%s \n",str2);getch();}

通过调用proc子函数实现。

子函数中a[ ]表示输入的原字符串。(可以用const修饰)

子函数中b[ ]表示删除字符后得到的字符串。

n表示删除字符的具体位置。

proc函数的具体实现如下:

void proc(char a[], char b[], int n){int i,k = 0;for (i = 0; a[i] != '\0'; i++){if ( i != n){b[k++] = a[i];}}b[k] = '\0';}

也可以这样

void proc(char a[], char b[], int n){int len = strlen(a);int i;for (i = 0; i < len; i++){if ( i < n){b[i] = a[i];}else{b[i] = a[i+1];}}b[len - 1] = '\0';}

结果显示如下:

完整代码如下:

#include <stdio.h>#include <windows.h>#include <conio.h>#define N 20void proc(char a[], char b[], int n);void main(){char str1[N], str2[N];int n;system("CLS");printf("Enter the string !\n");gets(str1);printf("Enter the position of the string deleted !\n");scanf("%d",&n);proc(str1,str2,n);printf("The new string is :%s \n",str2);getch();}void proc(char a[], char b[], int n){int len = strlen(a);int i;for (i = 0; i < len; i++){if ( i < n){b[i] = a[i];}else{b[i] = a[i+1];}}b[len - 1] = '\0';}

实现起来还是很简单的^_^

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。