Home > Net >  How to get a string within "\n" in c ?
How to get a string within "\n" in c ?

Time:07-17

Suppose I'm having-

string s="Hello Hi Hey\n""Bye Bye good night";

Now,I want to get the string within "\n" ,i.e I want to get "Hello Hi Hey"

How can i do so? I've thinking of stringstream, but it's not possible as "Hello Hi Hey" itself contains space.

CodePudding user response:

Now,I want to get the string within "\n" ,i.e I want to get "Hello Hi Hey"

How can i do so? I've thinking of stringstream, but it's not possible as "Hello Hi Hey" itself contains space.

Just instantiate a std::istringstream and use std::getline() to read the separate lines into strings:


string hellohihey;
string byebyegoodnight;
std::istringstream iss(s);
std::getline(iss,hellohihey);
std::getline(iss,byebyegoodnight);

Also note that the literal doesn't need separate double quotes:

string s="Hello Hi Hey\nBye Bye good night";

Or even use a raw string literal to get some kind of WYSIWYG feeling:

string s=R"(Hello Hi Hey
Bye Bye good night)";

CodePudding user response:

Clearly the std::istringstream / std::getline() solution is simpler in most cases, but it is possible to extract the lines using std::string alone. For example:

string s = "Line 1\nLine 2\nLine 3\n" ;

size_t beg = 0 ;
size_t end = 0 ;

// While lines remain to be processed...
while( end != string::npos && beg < s.length() )
{
    // Find end of line
    end = s.find( '\n', beg ) ;

    // Extract line excluding newline
    string single_line = s.substr( beg, end - beg ) ;

    // Show extraction and the start & end positions.
    cout << beg << " to " << end - 1 << " = \"" << single_line << "\"\n" ;

    // Set beginning of next line, skipping newline from previous
    beg = end   1 ;
}

Outputs:

0 to 5 = "Line 1"
7 to 12 = "Line 2"
14 to 19 = "Line 3"

For the simple case described in you question, the solution is simply:

string first_line = s.substr( 0, s.find( '\n' ) ) ;

Which will result in first_line == "Hello Hi Hey". So for simple cases it may not be necessary to instantiate a std::istringstream object.

  •  Tags:  
  • c
  • Related