how to get a specific text from string? #2

I don't do code much with c++ so here is a question I have with this string.
string - param 1: CP:0_PL:0_OID:_CT:[W]_ `6<`2Username``>`` `$`$Hello world!!````

I want to get the message "hello world" and nothing else.


1
2
3
4
5
6
7
8
9
  //I have tried something similar to my previous question 
std::string str = "param 1: CP:0_PL:0_OID:_CT:[W]_ `6<`2Username``>`` `$`$Hello world!!````";
    istringstream param1(str);
    std::string name;
    std::getline(param1, name, '$');
    std::getline(param1, name, '`'); // cannot really do that, since there will be ` before my message.

    std::cout << name << '\n';
 


Not really sure how I could get the string from there, really a pain.. Any suggestion?
Last edited on
Perhaps you want to give more details, constraints, and examples.
What exactly delimits what you want to parse out? Given that string, how do I know that I don't want to extract "Username" out of it, instead of "Hello World"?

Here's a short example that will find the first '$' in the string, extract everything after that string, and then remove the ` $ ! punctuation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Example program
#include <iostream>
#include <string>
#include <sstream>

std::string remove_punct(const std::string& str)
{
    std::string punct = "`$!";
    std::string ret;
    for (char ch : str)
    {
        if (punct.find(ch) == std::string::npos)
        {
            ret += ch;
        }
    }
    
    return ret;
}

int main()
{
    std::string str = "param 1: CP:0_PL:0_OID:_CT:[W]_ `6<`2Username``>`` `$`$Hello world!!````";
    
    auto index = str.find("$");
    if (index == std::string::npos)
    {
        // unable to parse message
        return 1;
    }
    
    std::string message = str.substr(index);
    message = remove_punct(message);
    std::cout << message << '\n';
    return 0;
}
Last edited on
Perhaps this may be a case where using a string, std::string rfind(), substr() might be of use?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    std::string str = "param 1: CP:0_PL:0_OID:_CT:[W]_ `6<`2Username``>`` `$`$Hello world!!````";

    // Find the last '$'
    size_t start = str.rfind('$');

    // Strip off the first character ('$').
    std::string message = str.substr(start + 1);

    std::cout << message << std::endl;

    // Now Strip off the '`' characters.
    message.erase(message.find('`'));

    std::cout << message << std::endl;


But be careful, if the searched characters don't exist then the substr() and erase() calls may throw an exception because the find/rfind functions return npos.
I just now read my post again and I think I could've presented the issue more clearly.
Anyways, the code solved the problem. Thanks for replying, have a nice day/night.
Registered users can post here. Sign in or register to post.