开发者

How can I separate a string in 3 shorts and the rest in one string (this string as white spaces in it) in C?

开发者 https://www.devze.com 2023-04-11 10:20 出处:网络
How can I separate a string that has white spaces between the 3 shorts and between the rest of the string to 4 different stri开发者_如何学Pythonngs.

How can I separate a string that has white spaces between the 3 shorts and between the rest of the string to 4 different stri开发者_如何学Pythonngs.

Example:

"123 402 10 aaa bbb cc".

What I want is simply

 short i=123;
 short j=402;
 short y=10;
 char * c="aaa bbb cc".

I was trying to use sscanf to do it but I can't seem to get the hang of getting that last string to work cause of the white space.


One way to do it could be:

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

int main()
{
    const char* str = "123 402 10 aaa bbb cc";
    short i,j,y;
    char c[256];
    if (sscanf(str, "%hd %hd %hd %255[^\n]", &i, &j, &y, c) == 4) {
        printf("i=%hd j=%hd y=%hd c=\"%s\"\n", i, j, y, c);
    }
    return 0;
}


It's not that difficult:

#include <stdio.h>

int main() {
  short i, j, y;
  char text[80];

  if (sscanf("123 402 10 aaa bbb cc\nsecond line", "%hd %hd %hd %79[^\n]", &i, &j, &y, text) == 4) {
    printf("success: i=%d, j=%d, y=%d, text=%s\n", i, j, y, text);
  }
  return 0;
}

Note that you have to allocate the buffer for the string yourself and make sure that no buffer overflow happens.


You don't need sscanf. You can use strchr to find the spaces, atoi to turn strings into integers, and simple assignment to turn the spaces into terminating zeroes.

You can also do this:

#include <stdio.h>
int main(void)
{
 const char *test="123 402 10 aaa bbb cc";
 short i, j, y;
 char c[128];
 sscanf(test, "%hd%hd%hd %[^\n]s", &i, &j, &y, c);
 printf("i=%d j=%d y=%d c='%s'\n", i, j, y, c);
}

Yields: i=123 j=402 y=10 c='aaa bbb cc'

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号