2

I am trying to split my string and the (\n)new line and want to get the new string without \n.My code is as below.Thanks.

token = strtok(NULL,"")  

The above snippet will store "some string and \n" where as I need just "some string".

My data looks like this.

1,v1,p1,182,1665,unkn
Nikko
  • 4,182
  • 1
  • 26
  • 44
Teja
  • 13,214
  • 36
  • 93
  • 155
  • 3
    Use std::string and the algorithms to do it in C++. Much safer. – DumbCoder Nov 16 '12 at 12:43
  • @Daniel It is printing NULLS – Teja Nov 16 '12 at 12:46
  • You should look into http://stackoverflow.com/questions/236129/splitting-a-string-in-c to see how to do this in C++. – Björn Pollex Nov 16 '12 at 12:46
  • @SOaddict You have done a `strtok(your_string, separators);` before that? The `NULL` as first argument is for calls to `strtok` after the first. And you must of course check whether `token` is `NULL`, at which point you've reached the end of the input string. – Daniel Fischer Nov 16 '12 at 12:49
  • Yes I am at the end of my input string.My data looks like this "1,v1,p1,182,1665,unkn".I am trying to extract "unkn" from this input. – Teja Nov 16 '12 at 12:52

2 Answers2

3

If you data looks like this

char line[] = "1,v1,p1,182,1665,unkn\n";

you could do something like this (in C)

char* p = line + strlen(line) - 1;
for (;*p != ','; --p) 
{
  ;
}
char* lastword = strtok(p + 1,"\n"); 
AndersK
  • 35,813
  • 6
  • 60
  • 86
  • That's valid C99, but many compilers will prefer the `lastword` declared at the top (but still assigned at the bottom, of course). – ams Nov 16 '12 at 13:30
  • And it would be better to use a standard function like `strrchr` to find the last comma. – ams Nov 16 '12 at 13:33
0

If all you are doing is replacing the first newline then this is much better:

char *tmp = strchr (str, '\n');
if (tmp) *tmp = 0;

If you are replacing the last newline in the string then this is better:

char *tmp = strrchr (str, '\n');
if (tmp) *tmp = 0;
Patrick Schlüter
  • 11,394
  • 1
  • 43
  • 48
Lelanthran
  • 1,510
  • 12
  • 18