华为新版oj的第一题,新版好多bug!还是喜欢老版本的界面,新版本这么小清新的界面不适合我。
代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
getline(cin,str);
int pos = 0,npos = -1;
pos = str.find_last_of(' ');
if(pos == npos)
cout << str.size() << endl;
else
cout << (str.size() - (pos+1)) << endl;
return 0;
}
string 类提供字符串处理函数:
利用这些函数,程序员可以在字符串内查找字符,
提取连续字符序列(称为子串),以及在字符串中删除和添加。
1.函数find_first_of()和 find_last_of() 执行简单的模式匹配
例如:在字符串中查找单个字符c。
函数find_first_of() 查找在字符串中第1个出现的字符c,而函数find_last_of()查找最后
一个出现的c。匹配的位置是返回值。如果没有匹配发生,则函数返回-1.
int find_first_of(char c, int start = 0):
查找字符串中第1个出现的c,由位置start开始。
如果有匹配,则返回匹配位置;否则,返回-1.默认情况下,start为0,函数搜索
整个字符串。
int find_last_of(char c):
查找字符串中最后一个出现的c。有匹配,则返回匹配位置;否则返回-1.
该搜索在字符末尾查找匹配,所以没有提供起始位置。
string str = "Mississippi";
int index;
// 's ' 在index 为 2、3、5、6处出现
index = str.find_first_of('s',0); // index为 2
index = str.find_first_of('s',4); // index为 5
index = str.find_first_of('s',7); // index为 -1
// ‘s’的最后出现在 index= 6
index = str.find_last_of('s');
// while 循环输出每个'i'的index
while((index = str.find_first_of('i', index))!= -1)
{
cout << "index" << index << " ";
index++; // restart search at next indx
}
更多 string 类提供字符串处理函数参考:http://blog.csdn.net/zhenyusoso/article/details/7286456