2

how can I split a multi-line string in const char* array.?

Here is the input string.

const char* str = "122.123,-38.789"
                  "122.123,-39.78";

I need to get two string from this.

str1 = "122.123,-38.789";

str2 = "122.123,-39.78";

output of

printf("string='%s'", str)

string='122.123,-38.789122.123,-39.78'

What should be done to split this string ?

rkm
  • 892
  • 2
  • 16
  • 32
  • 4
    There's no way to do this if you don't separate the strings somehow with a delimiter character or something. The way you're doing it, both strings are being merged into one, and because there's no delimiter character, there's also no way back. – 3442 Mar 17 '16 at 04:19
  • Do you have control over `str`'s declaration? Could you add a newline or other delimiter at the end? `"122.123,-38.789\n"`, e.g. – Brian Cain Mar 17 '16 at 04:26
  • @BrianCain, no i can't modify str. it is set by user. I guess the input must be considered invalid. – rkm Mar 17 '16 at 05:04
  • 1
    Something is afoul here. Is it set by user or is it `const char*`? Can you post something closer to the real code? – technosaurus Mar 17 '16 at 05:18

1 Answers1

5

Use an array of char *

#include <stdio.h>
const char* str[] = { "122.123,-38.789" ,  "122.123,-39.78" };

int main(){
  printf("%s\n%s\n",str[0],str[1] );
  return 0;
}

How the compiler understood your code:

The C pre-processor concats strings placed together,

const char* str = "122.123,-38.789"
                  "122.123,-39.78";

The linebreak between the strings is parsed as a blank, treated the same as a space or a tab. So it's equivalent to:

const char* str = "122.123,-38.789" "122.123,-39.78";

which the preprocessor converts to

const char* str = "122.123,-38.789122.123,-39.78";
Community
  • 1
  • 1
xvan
  • 4,554
  • 1
  • 22
  • 37