Get last word of the string We have to print the last word of the given string. How to improve and optimise this code?

#include &lt;iostream&gt;

std::string get_last_word(const std::string&amp; str)
{
    if (str.length() == 0)
    {
        std::cerr &lt;&lt; "No string\n";
        return 0;
    }

    int len = str.length();
    int i = len - 1;
    while (i &gt;= 0 &amp;&amp; str[i] != ' ')
    {
        i--;
    }
    std::string last_word;
    for (int j = i + 1; j &lt; len; j++)
    {
        last_word += str[j];
    }
    return last_word;
}

int main()
{
    std::string str;
    std::cout &lt;&lt; "Enter string :\n";
    std::getline(std::cin, str);
    std::cout &lt;&lt; "Last word :\n";
    std::cout &lt;&lt; get_last_word(str);
    std::cout &lt;&lt; std::endl;
}
Be careful with types. For example, your get_last_word function is meant to return a string but in your error case you return 0. If you want to return an empty string, use return "";

I'm guessing that you might be working under restrictions about what library functions you're allowed to use here, but you don't say so. 

If you're allowed to use anything in the standard library, have a look at std::string::find_last_of as a replacement for your first loop. 

Similarly, look at std::string::substr as a replacement for your second loop. Building a string one character at a time is generally discouraged because it's quite inefficient. Something like substr will be more efficient because it can, for example, allocate all the memory needed by your string in one go.