比如说删除字符串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';}
实现起来还是很简单的^_^