读书人

从string对象中去除标点符号.解决方案

发布时间: 2012-04-04 16:38:51 作者: rapoo

从string对象中去除标点符号.
有一道题:
编一个程序,从string 对象中去掉标点符号。要求输入到程序的字符串必须含有标点符号,输出结果则是去掉标点符号的string对象.如何实现,有简单易懂的程序实现。

[解决办法]
#include <iostream>
#include <string>
using namespace std;
int main()
{
string filter( "\ ",.;:?!)(\\/ ");
string inputString;
cin> > inputString;

string::size_type pos=0;
while((pos = inputString.find_first_of(filter,pos)) != string::npos)
{
inputString.erase(pos,1);
}

cout < <inputString;
return 0;
}
[解决办法]
int main()
{
string str;
cout < < "Please enter a string: ";
cin > > str;
cout < < endl;

string caps( ",.\ '\ " ");

string::size_type pos = 0;
while ((pos = str.find_first_of(caps, pos)) != string::npos)
{
str.erase(pos, 1);
}
cout < < str < < endl;
return 0;
}
[解决办法]
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout < < "Please enter a string: ";
cin > > str;
cout < < endl;

string filter( "\ ",.;:?!\ ' ");

string::size_type pos = 0;
while ((pos = str.find_first_of(filter, pos)) != string::npos)
{
str.erase(pos, 1);
}
cout < < str < < endl;
return 0;
}
[解决办法]
一思路:
string str = "my name is zhao,and i 'm ten years old. ";
string strDes = " ";
for (int n = 0; n < str.length(); n++)
{
char cTmp = str.at(n);
if ((cTmp > 47 && cTmp < 58) || (cTmp > 64 && cTmp < 91) || (cTmp > 96 && cTmp < 123))
{
strDes += cTmp;
}
}
cout < < strDes;
[解决办法]
bool NotNeed(char c)
{
return ispunct(c) || isspace(c);
}
int main()
{
string s( "my name is zhao,and i 'm ten years old. ");
s.erase(remove_if(s.begin(), s.end(), NotNeed), s.end());
cout < < s;

system( "pause ");
return 0;
}
[解决办法]
#include <iostream>
#include <string>
#include <functional>
#include <algorithm>
using namespace std;

struct Filter:public unary_function <char,bool>
{
public:
Filter(const string& f):filter(f){}
bool operator()(char ch) const {return filter.find(ch)!=string::npos;}
private:
string filter;
};
int main()
{
Filter F( "\ ",.;:?!)(\\/ ' ");
string inputString;
getline(cin,inputString);

inputString.erase(remove_if(inputString.begin(),inputString.end(),F),inputString.end());

cout < <inputString;
return 0;
}

G:\test> a
Hello,This a demo of csdn 's question!
HelloThis a demo of csdns question
G:\test>

[解决办法]
public class myString
{
public static void main(String [] args)
{
String s = "My,Name.Is!Xu! ";

char [] chs = s.toCharArray();

for(int i=0;i <chs.length;i++)
{
if(Character.isDigit(chs[i])==false && Character.isLetter(chs[i])==false)
{
chs[i]= '\0 ';
}
}

String newString = String.valueOf(chs);
System.out.println(newString);
}
}

读书人网 >C++

热点推荐