c++编程:从字符串中删除指定的字符

编写函数fun( ),该函数功能是从字符串中删除指定的字符,同一字母的大小写按不同的字符处理。 例如:执行时输入的字符串是 turbo c and borland c++,从键盘上输入字符n,则输出为 turbo c ad borlad c++. 如果输入的字符在字符串中不存在,则原样输出。仅在函数fun的花括号中填入所编写的语句.
#include<iostream.h>
using namespace std;
void fun(char s[],int c)
{
}
int main()
{
static char str[]="turbo c and borland c++";
char ch;
cout<<"原始字符串:\n"<<str<<endl;
cout<<"输入一个字符:“;
cin>>ch;
fun(str,ch);
cout<<"str="<<str<<endl;
return 0;
}

我对这些都是一片茫然的,知道的麻烦教我一下~非常感谢!!

#include<iostream>

#include<string.h>

usingnamespacestd;

intmain(){

strings="-daas-j--kdj-al-";

string::iteratorit;

for(it=s.begin();it!=s.end();it++)

if(*it=='-'){

s.erase(it);

it--;

}

cout<<s<<endl;

return0;

}

扩展资料

C++从string中删除一个字符

#include<iostream>

#include<string>

#include<stdlib.h>

usingnamespacestd;

intmain()

{

stringstr="abddghj";

string::iteratorit;//指向string类的迭代器。你可以理解为指针

for(it=str.begin();*it!='';it++)

{

if(*it=='d')

{

str.erase(it);//删除it处的一个字符

break;

}

}

cout<<str<<endl;

system("pause");

return0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-12-16
原始字符串:
turbo c and borland c++
输入一个字符:c
str=turbo and borland ++
Press any key to continue

这就是你写的定义 ? void fun(char s[],int c) 第二个参数是 int?! 哎 无语 谁知道你还把哪里写错着

#include<iostream>
using namespace std;

void *fun(char * const str,const char ch) //从str字符串删除所有的todel字符,返回处理后的字符串地址
{
int i,j;
for (i = 0; str[i];) {
if (str[i]==ch) {
for (j=i; str[j]; j++) {
str[j]=str[j+1];
}
}
else i++;
}
return str;
}

int main()
{
static char str[]="turbo c and borland c++";
char ch;
cout<<"原始字符串:\n"<<str<<endl;
cout<<"输入一个字符:";
cin>>ch;
fun(str,ch);
cout<<"str="<<str<<endl;
return 0;
}本回答被提问者采纳
第2个回答  2011-06-17
char *fun( char s[] , const char ch )
{
int len = strlen ( s ) , j = 0 , k = 0/*新字符串的下标*/ ;
for (j = 0 ; j < len ; j++)
{
if (s [ j ] == ch ) continue;
s [ k++ ] = s[ j ];
}
s [ k++] = '\0';

return s;/*设置一个返回值有益于函数的链式表达*/
}
第3个回答  2011-06-17
#include<iostream>
#include<string>
using namespace std;
void fun(char s[],char c)
{
for (int i=0;i<strlen(s);)
{
if (s[i]==c)
{
s[i]=s[i+1];//将目标字符的后一个字符前移 就覆盖了目标字符
}
else
{
++i;
}
}
}
int main()
{
const int n=1000;//为要输入的turbo c and borland c++字符串提供足够大的空间
static char str[n];
gets(str); //char 是C风格的字符串所以用gets函数来输入包括空格在内的字符串
char ch;
cout<<"原始字符串:\n"<<str<<endl;
cout<<"输入一个字符:";
cin>>ch;
fun(str,ch);
cout<<"str="<<str<<endl;
return 0;
}
第4个回答  2011-06-17
#include<iostream>
using namespace std;
void fun(char s[],char c)
{
int len=sizeof(s);
for(int i=0;i<len;i++)
{
if(s[i]==c)
{
for(int j=i;j<len;j++)
{
s[j]=s[j+1];
}
i--;
}
}

cout<<s<<endl;
}
int main()
{
char str[]="turbo c and borland c++";
char ch;
cout<<"原始字符串:\n"<<str<<endl;
cout<<"输入一个字符: ";
cin>>ch;
fun(str,ch);
cout<<str<<endl;
return 0;
}
相似回答