C++ Split String by Line

How to split a string literal across multiple lines in C / Objective-C?

There are two ways to split strings over multiple lines:

  1. Each string on its own line. Works only with strings:

    • Plain C:

      char *my_string = "Line 1 "
      "Line 2";
    • Objective-C:

      NSString *my_string = @"Line1 "
      "Line2"; // the second @ is optional
  2. Using \ - can be used for any expression:

    • Plain C:

      char *my_string = "Line 1 \
      Line 2";
    • Objective-C:

      NSString *my_string = @"Line1 \
      Line2";

The first approach is better, because there isn't a lot of whitespace included. For a SQL query however, both are possible.

NOTE: With a #define, you have to add an extra \ to concatenate the two strings:

Plain C:

#define kMyString "Line 1"\
"Line 2"

In C, How to split a string on \n into lines

strstr just returns a pointer to the first match of second argument.

Your code is not taking care of null character.

Can use strcpy to copy string.

while (p) {
// Also you want string only if it contains "likes"

if (strstr(p, token))
{
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1);
res[n_spaces-1] = malloc(sizeof(char)*strlen(p));

strcpy(res[n_spaces-1],p);
}
p = strtok (NULL, "\n");
}

Free res using:

for(i = 0; i < n_spaces; i++)
free(res[i]);
free(res);

Split string with delimiters in C

You can use the strtok() function to split a string (and specify the delimiter to use). Note that strtok() will modify the string passed into it. If the original string is required elsewhere make a copy of it and pass the copy to strtok().

EDIT:

Example (note it does not handle consecutive delimiters, "JAN,,,FEB,MAR" for example):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;

/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}

/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);

/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;

result = malloc(sizeof(char*) * count);

if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);

while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}

return result;
}

int main()
{
char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
char** tokens;

printf("months=[%s]\n\n", months);

tokens = str_split(months, ',');

if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("month=[%s]\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}

return 0;
}

Output:

$ ./main.exe
months=[JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC]

month=[JAN]
month=[FEB]
month=[MAR]
month=[APR]
month=[MAY]
month=[JUN]
month=[JUL]
month=[AUG]
month=[SEP]
month=[OCT]
month=[NOV]
month=[DEC]

C++ split string by line

I'd like to use std::getline or std::string::find to go through the string.
below code demonstrates getline function

int doSegment(char *sentence)
{
std::stringstream ss(sentence);
std::string to;

if (sentence != NULL)
{
while(std::getline(ss,to,'\n')){
cout << to <<endl;
}
}

return 0;
}

Parse (split) a string in C++ using string delimiter (standard C++)

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token.

Example:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
  • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.

  • The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos.


If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());):

s.erase(0, s.find(delimiter) + delimiter.length());

This way you can easily loop to get each token.

Complete Example

std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

Output:

scott
tiger
mushroom

How to split a string to 2 strings in C

#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";

// Token will point to "SEVERAL".
token = strtok(line, search);

// Token will point to "WORDS".
token = strtok(NULL, search);

Update

Note that on some operating systems, strtok man page mentions:

This interface is obsoleted by strsep(3).

An example with strsep is shown below:

char* token;
char* string;
char* tofree;

string = strdup("abc,def,ghi");

if (string != NULL) {

tofree = string;

while ((token = strsep(&string, ",")) != NULL)
{
printf("%s\n", token);
}

free(tofree);
}

C# Unable to split string by new lines \n

Sometimes when you see a \n on screen it really is a backslash (ASCII 92 and an en(ASCII 110) not a placeholder/escape sequence for new line (ASCII 10) A big hint for that here is that text boxes will usually not display newlines with escape codes but will put in actual new lines.

To split on \n use the string "\\n" which represents a string of two characters: the two backslashes produce a single character ASCII 92 = '' in the string and then a lowercase n.

Alternately you could use @"\n". The @ sign tells C# not to use escape codes in the quoted string.

C: trying to split fprintf() format string into multiple lines with line-continuation using \ adds tabs at the beginning of lines that follow

You do not need \ as it is not a macro definition.

Simply have as many as you want as string literals separated by as many as you want whitespace (new line is also a whitespace). The C compiler ignores the whitespace.

int main(void)
{
fprintf(stdout, "This program take a date supplied by the user in dd/mm/yyyy format...\n"
"And returns the day of the week for that date using Zeller's rule.\n\n"
"Enter date in (dd/mm/yyyy) format: ");
}
int main(void)
{
fprintf(stdout, "This program take a date"
" supplied by the user in dd/"
"mm/yyyy format...\n"
"And returns "
"the "
"day of "
"the "




"week for that "
"date using Zeller's rule.\n\n"
"Enter date in (dd/mm/yyyy) format: ");
}

https://godbolt.org/z/6ovj3G



Related Topics



Leave a reply



Submit