64,685
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <strstream>
#include <string>
using namespace std;
int str_len(const char* str)
{
istrstream is(str);
string last;
while (is >> last);
return last.size();
}
int main()
{
char s1[100];
cout << "input a string:";
cin >> ws;
cin.getline(s1,100);
int i = str_len(s1);
cout << i << endl;
}
int findword(const char *pch)
{
char *p = (char *)pch;
char *t;
if (pch[0] == '\0')
return 0;
// 跳到句尾
while (*(++p));
// 过滤字符
while (!(*p >= 'a' && *p <= 'z') &&
!(*p >= 'A' && *p <= 'Z'))
p--;
// 记住最后一个字母的位置
t = p;
// 向前搜索空格或句子第一个字母
while (*p != ' ' || p == pch)
p--;
return t - p;
}
int main()
{
const char *pch = "My name is Sandrer.";
int n = findword(pch);
printf("%s\nword size: %d\n", pch, n);
system("pause");
return 0;
}
int n;
string s;
while(cin>>s) n=s.size();
cout<<n<<endl;
#include "boost/algorithm/string.hpp"
#include <vector>
#include <iostream>
int main()
{
std::string s = "hello world";
std::vector<std::string> v;
boost::split(v, s, boost::is_any_of(" "));
std::cout << v.back().size();
return 0;
}
注意:没有考虑最后一个单词后面有标点符号的问题int str_len(const string& str)
{
if("" == str)
return 0;
istringstream is(str);
string last;
while (is >> last) ;
return last.size();
}