-1

Hi I need to find second to last word in a string. Right now below program is printing the last one.

#include <iostream>
#include <string>

using namespace std;

int main() {
    string text{"some line with text"};
    // find last space, counting from backwards
    int i = text.length() - 2; // last character
    while (i != 0 && !isspace(text[i]))
    {
      --i;
    }
    string lastword = text.substr(i+1); // +1 to skip leading space
    cout << lastword << endl;
    return 0;
}  

Output: (Printing last word)

text
gaurav bharadwaj
  • 1,669
  • 1
  • 12
  • 29

3 Answers3

2

You can split the string into words and hold the previous word before saving the current word.

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string text{"some line with text"};
    std::stringstream ss(text);
    std::string previousword, lastword, newword;
    while (ss >> newword) {
        previousword = lastword;
        lastword = newword;
    }
    std::cout << previousword << std::endl;
    return 0;
}

Also note that using using namespace std; is discouraged.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

You don't need any loops. Just add error checking:

int main() {
  std::string text{ "some line with text" };
  std::size_t pos2 = text.rfind(' ');
  std::size_t pos1 = text.rfind(' ', pos2-1);

  std::cout << text.substr(pos1+1, pos2-pos1-1) << std::endl;
  return 0;
}
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
0

Just keep counting spaces until you arrive to the word you want or use a stringstream as MikeCAT proposed.

Here there is a function that finds any last word number without having to copy the entire string in a stringstream:

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;

string getNLastWord(string text, int n)
{
    bool insideAWord = false;
    int wordNum = 0;
    int wordEnd = -1;
    for(int i = text.size() - 1; i > 0; i--)
    {
        if(text[i] != ' ' && !insideAWord)
        {
            wordNum++;
            insideAWord = true;
        }
        else if(text[i] == ' ')
        {
            insideAWord = false;
        }
        if(wordNum == n)
        {
            wordEnd = i;
            break;
        }
    }
    if(wordEnd == -1)
    {
        cout << "There are no " << n << " words from right." << endl;
    }
    else
    {
        int wordStart;
        for(wordStart = wordEnd; wordStart > 0; wordStart--)
        {
            if(text[wordStart] == ' ')
            {
                wordStart++;
                break;
            }
        }
        return text.substr(wordStart,wordEnd+1-wordStart);
    }
    return "";
}

int main() {
    string text = "some text";
    cout << getNLastWord(text,2);
    return 0;
}
Gary Strivin'
  • 908
  • 7
  • 20