Ho to get a string till the last occurrence of a character

Viewed 355

EDIT 1

I forgot to say that the string has to be taken from cin

I have a string like "Hi; my;; name is Andrea; and I like C++". I want to create a stringstream initialized with that string and get everything before the last ;.

This is what I've tried:

    string ex("Hi; my;; name is Andrea;; and I like C++"), text, final_text;
    stringstream loop_stream(ex);
    int findComma = loop_stream.str().find(';');
    do {
        getline(loop_stream, text, ';');
        loop_stream.ignore(1);
        final_text += text;
        loop_stream << loop_stream.rdbuf();
        findComma = loop_stream.str().find(';');
        while (findComma == 1) {
            loop_stream.ignore(1);
        }
        findComma = loop_stream.str().find(';');
    }
    while (findComma != string::npos);

    cout << "-" << final_text << "-" << endl;

but it doesn't work at all... I would like the output to be:

-Hi; my;; name is Andrea-
4 Answers

Here is another solution using find_last_of:

#include <string>
#include <iostream>

int main()
{
   std:: string test = "Hi; my;; name is Andrea; and I like C++";
   auto pos = test.find_last_of(";");
   if ( pos != std::string::npos)
      std::cout << test.substr(0, pos);
}

Output:

Hi; my;; name is Andrea

Using a function:

#include <string>
#include <iostream>

std::string parseString(const std::string& s)
{
   auto pos = s.find_last_of(";");
   if ( pos != std::string::npos)
      return s.substr(0, pos);
   return s;
} 

int main()
{
   std::cin >> test;  // assume the string will be inputed
   std::cout << parseString(test);
}

How about something simpler, not using stringstream:

string ex("Hi; my;; name is Andrea;; and I like C++");
size_t pos = ex.rfind(';'); // find last semicolon
string final_text = ex.substr(0, pos);

You can use an istreambuf_iterator to construct a string from everything that is in the istream (like std::cin). After that, just use one of the other answers to extract what you want:

#include<iostream>
#include<iterator>
#include<sstream>

int main(){
    std::istringstream loop_stream("Hi; my;; name is Andrea;; and I like C++");

    // read the stream until it's depleted and put it in a string:
    std::string all_stream(std::istreambuf_iterator<char>(loop_stream),
                           std::istreambuf_iterator<char>{});

    // use any of the other answers, like this:

    std::string final_text;
    if(auto pos = all_stream.find_last_of(";"); pos != all_stream.npos) {
        final_text = all_stream.substr(0, pos);
    }

    std::cout << '-' << final_text << "-\n";
}

Output:

-Hi; my;; name is Andrea-

you are stuck in repeating loop, check your condition of loop. I think there is some problem with findComma it's value isn't updating.

Related