-
Notifications
You must be signed in to change notification settings - Fork 0
/
lastwordlength.cpp
57 lines (53 loc) · 1.25 KB
/
lastwordlength.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<string>
#include<iostream>
int lengthOfLastWord(string s) {
int len = s.length();
if (len==0)
return 0;
if (len == 1 && s[0] ==' ')
return 0;
if (len == 1 && s[0]!=' ')
return 1;
int i=0;
int j=0;
string sub_str;
while(s[j]==' ' && j<len)
{
j++;
}
if (j == len)
return 0;
i = j;
sub_str = s.substr(i, len-i);
len = sub_str.length();
i = 0;
while(len>0)
{
std::size_t found = sub_str.find(' ');
j = found;
if(found!= std::string::npos)
{
while (sub_str[j]==' ' && j<len)
j++;
if (j == len)
return found-i;
else
{
i = j;
}
}
else
{
return len;
}
sub_str = sub_str.substr(i, len-i);
std::cout<<"sub_str........"<< sub_str <<"\n";
len = sub_str.length();
i = 0;
}
}
int main()
{
string s = "This is a nice day";
std::cout<< lengthOfLastWord(s);
}