![]() |
#2
pangding2011-02-02 00:19
|

#include <iostream>
#include <cctype>
#include <string>
using namespace std;
void main()
{
string str ;
string words;
cout<<"please input string"<<endl;
std::getline(cin,str);
cout <<"please input words"<<endl;
cin>>words;
size_t wordsLength = words.length();
size_t pos ;
for (size_t i = 0 ; i<str.length() ; i=pos + wordsLength)
{
pos = str.find(words,i);
if (pos == string::npos)
{
break;
}
if (pos == 0)
{
str.replace(pos,wordsLength,wordsLength,'*');
}
size_t prepos = pos -1;
size_t lasrpos = pos+wordsLength+1;
if ((prepos,1," ") == 0&&(lasrpos,1," "))
{
str.replace(pos,wordsLength,wordsLength,'*');
}
}
cout<<str<<endl;
}
目的就是在一个指定的字符串中替换制定单词为***。现在我想进行一下大小写转换。比如str=“What your name”,你要替换的单词输入时是words=what(这里的w是小写的),这样也能替换成功。或者更复杂点,比如str=“WHAT your name”,words=what(都是小写),这样也能替换WHAT为****。#include <cctype>
#include <string>
using namespace std;
void main()
{
string str ;
string words;
cout<<"please input string"<<endl;
std::getline(cin,str);
cout <<"please input words"<<endl;
cin>>words;
size_t wordsLength = words.length();
size_t pos ;
for (size_t i = 0 ; i<str.length() ; i=pos + wordsLength)
{
pos = str.find(words,i);
if (pos == string::npos)
{
break;
}
if (pos == 0)
{
str.replace(pos,wordsLength,wordsLength,'*');
}
size_t prepos = pos -1;
size_t lasrpos = pos+wordsLength+1;
if ((prepos,1," ") == 0&&(lasrpos,1," "))
{
str.replace(pos,wordsLength,wordsLength,'*');
}
}
cout<<str<<endl;
}
在上面的基础上怎么修改?