Message from C, C++ discussions

December 2019

— Could you please reply to this this

— 

Given a string s consists of upper/lower-case alphabets and empty space characters ' ',. Return the length of last word in the string. If the last word does not exist, return 0.

#include<bits/stdc++.h>
using namespace std;
int last_word(string str)
{
int len=str.length();
int count=0,count_space=0;
for(int i=0;i<len;i++)
{
if(str[len-1-i]!=' ')
count++;
else
{
count_space++;
break;
}
}
if(count_space!=0)
return count;
else
return -1;
}
int main()
{
string str;
cout<<"Enter the string : ";
getline(cin,str);
cout<<last_word(str);
return 0;
}

— Some of my test cases are not passing.... Can anyone help me out?

— That count_space variable is not doing anything

— Just stop counting once you hit a space or the reverse end of the string

— I am using it to check the occurence of first space.... The loop will break if a space occurs.

— Let me try

— And why are you returning -1?

— Sorry it should be return 0, I just returned -1 to get better idea

— If you think for a moment, you don't need that last condition

— Yeah, it worked now...... I have been so foolish.... Thank you so much

— I removed the count_space and the last condition