find the last word in a string

Dec 30, 2015 at 6:31am
I assumed that there would be functions to cover a lot of these string operations I've been doing lately but... Here is my newest problem.

I am writing a function that finds the last word in a string but not getting the results. What i have done is to find the last character in the string by getting the size.
I next use the function isspace(c) so once there is a space the loop breaks where the string variable "store" stores the characters of the last word in reverse order. But for some reason the function reverse is not reversing the character sequence.

here is the code:

include<stdio.h>
#include<ctype.h>
#include <iostream>
#include <string>

using namespace std;


int main()
{ char c; string store;

string str =" reverse string";
int i = str.size()-1;

while(str[i])
{
c=str[i];


if(isspace(c))
{ break;
}

cout<<c;
i--;

store.push_back(c);
reverse(store.begin(),store.end());
}

cout<<endl<<store;


return 0;
}

Here is the result:

(output) gnirts
(after using reverse function) srngit
Dec 30, 2015 at 6:52am
1
2
3
4
5
6
7
8
9
std::string last_token( std::string str )
{
    while( !str.empty() && std::isspace( str.back() ) ) str.pop_back() ; // remove trailing white space
    
    const auto pos = str.find_last_of( " \t\n" ) ; // locate the last white space
    
    // if not found, return the entire string else return the tail after the space
    return pos == std::string::npos ? str : str.substr(pos+1) ;
}
Dec 30, 2015 at 7:47am
I've seen where you've sort of offset the last set of character with reference to the last white space(line 5) to store the position. How would you instead locate the last backslash instead of the white space?
Dec 30, 2015 at 7:54am
Man, how do you know all this
no worries I found it though, thanks again
str.find_last_of("/\\");
Dec 31, 2015 at 4:35am
just posting the solution, found the problem in original code.
the reverse function was in the while loop should be outside:

#include<algorithm>
using namespace std;


int main()
{ char c; string store;

string str =" reverse string";
int i = str.size()-1;

while(str[i])
{
c=str[i];


if(isspace(c)){ break;}

i--;

store.push_back(c);
}
reverse(store.begin(),store.end());
cout<<endl<<store;



return 0;
}
Dec 31, 2015 at 4:58am
Same logic as above (reverse the string, read first token from the reversed string, and reverse the token):

1
2
3
4
5
6
7
8
9
10
std::string last_token( std::string str )
{
    std::string token ;

    // read the first token from an input string stream constructed with the string in reverse
    std::istringstream( { str.rbegin(), str.rend() } ) >> token ; // #include <sstream>

    // return the reverse of the token that was read
    return { token.rbegin(), token.rend() } ;
}

http://coliru.stacked-crooked.com/a/2346aee245545b49
Topic archived. No new replies allowed.