P037 删除字符串中指定下标的字符 ★★

03-程序设计题 软件121, 唐鼎威 1194浏览

所属年份:2010.9;2011.9;2012.3
编写函数fun,其功能是:删除一个字符串中指定下标的字符。其中,a指向原字符串,删除指定字符后的字符串存放在b所指的数组中,n中存指定的下标。
例如,输入一个字符串world,然后输入3,则调用该函数后的结果为word。

#include <stdio.h>
#include <string.h>
#define LEN 20

void fun (char a[], char b[], int n)
{


}

main( )
{   char str1[LEN], str2[LEN] ;
    int n ;

    printf("Enter the string:\n") ;
    gets(str1) ;
    printf("Enter the position of the string deleted:") ;
    scanf("%d", &n) ;
    fun(str1, str2, n) ;
    printf("The new string is: %s\n", str2) ;
}

【考点分析】
本题考查:删除字符串中指定字符,我们一般采用保留非指定字符的方法。
【解题思路】
本题要求删除字符串中指定下标的字符,即把非指定下标的字符保留,所以if语句条件表达式的内容是if(i!=n)。字符串最后不要忘记加上字符串结束标识’\0’。

【参考答案】

void fun (char a[], char b[], int n)
{
int i,k=0;
  for(i=0;a[i]!='\0';i++)
     if(i!=n)          /*将不是指定下标的字符存入数组b中*/ 
        b[k++]=a[i];
  b[k]='\0';  /*在字符串最后加上结束标识*/ 
}