用字符串查找第一个非的c ++麻烦

时间:2013-11-13 21:01:27

标签: c++ string

嗨我想将字符从一个点打印到另一个点 例如

string str = "what is o and o this "; //I want to print all the 
                        //characters [ O and O ]
string temp1;
int loc1, loc2;
loc1 = str.find_first_not_of('o');
loc2 = str.find_last_not_of('o');
temp1 = str.substr(loc1, loc2);
cout << temp1 << endl; //this prints out entire string
谁能帮助我? 谢谢你的帮助!!

1 个答案:

答案 0 :(得分:2)

你应该使用find_first_of/find_last_of函数,substr的第二个参数需要长度,而不是位置:

string str = "what is o and o this "; //I want to print all the 
                        //characters [ O and O ]
string temp1;
int loc1, loc2;
loc1 = str.find_first_of('o');
if( loc1 == string::npos ) return; // symbol not found
loc2 = str.find_last_of('o');
temp1 = str.substr( loc1, loc2 - loc1 + 1 );
cout << temp1 << endl; //this prints out entire string