Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
从键盘输入一个字符串给str和一个字符给c,删除str中的所有字符c并输出删除后的字符串str。
Input
第一行是一个字符串,不超过100个字符;
第二行是一个字符。
Output
删除指定字符后的字符串。
Sample Input
sdf
s
d
f
sdf
sdf$
$
Sample Output
sdfsdf
Hint
Source
**本题可以考虑数组中的元素删除方法,即:再循环读取每一个元素时,若为所找元素,则其后面的元素全部向前移一位;
方法一:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[101],s;
int n,i,j;
gets(a);
scanf("%c",&s);
n = strlen(a); //计算字符串的长度;
for(i=0;i<n;i++)
{
if(a[i]==s)
{
for(j=i;j<=n;j++) /*若为删除元素
则其后面的所有元素向前移一位,注意“=”,要将“/0”一起向前移动*/
{
a[j] = a[j+1];
}
i--; /*“注意”此处,
若没有,在有几个删除元素相邻时无法全部删除*/
}
}
puts(a);
return 0;
}
运行结果:
sdf$$$sdf$$
$
sdfsdf
Process returned 0 (0x0) execution time : 5.511 s
Press any key to continue.
**也可以考虑用两个数组,这样容易理解,代码易实现:
方法二
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s,a[101],b[101];
int n,i,k=0;
gets(a);
scanf("%c",&s);
n = strlen(a);
for(i=0;i<=n;i++) //注意“=”,要将“\0”一起复制到b数组中;
{
if(a[i]!=s)
b[k++] = a[i];
}
puts(b);
return 0;
}
运行结果:
sdf$$$sdf$$
$
sdfsdf
Process returned 0 (0x0) execution time : 7.512 s
Press any key to continue.