简体   繁体   English

如何在C中将一个字符串分为3个短裤,其余部分分为一个字符串(此字符串为空格)?

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

How can I separate a string that has white spaces between the 3 shorts and between the rest of the string to 4 different strings. 如何将3个短裤之间以及其余字符串与4个不同字符串之间具有空格的字符串分隔开。

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. 我试图使用sscanf来做到这一点,但似乎无法让最后一个字符串起作用而导致空白。

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 . 您不需要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. 您可以使用strchr查找空格,使用atoi将字符串转换为整数,并使用简单赋值将空格转换为终止零。

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' 产量: i=123 j=402 y=10 c='aaa bbb cc'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM