如何在c中有效地解析字符串

har*_*ari 2 c string char

我有:

char *str = "abc def  abcdef ghi   xyz";
Run Code Online (Sandbox Code Playgroud)

我想分配

const char *a = "abc"; 
const char *b = "def";
const char *c = "abcdef";
const char *d = "ghi";
const char *e = "xyz";
Run Code Online (Sandbox Code Playgroud)

这里的关键是空格数可以多于一个.

请建议一个有效的方法.

Oli*_*rth 7

效率是旁观者的眼睛.但看一看strtok; 但是,您需要使用可以修改的字符串副本.

请注意,这char *str = "blah"不是一个好主意.你应该使用const char *str = "blah".


Pra*_*ian 5

这是一些使用的示例代码strok_r.它是可重入的版本strtok(不确定它是否是C标准的一部分).另外,我假设你只有5个令牌.如果你想拥有更多,你将不得不修改代码以使用分配额外的内存realloc.

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

int main(void)
{
  const char *str = "abc def  abcdef ghi   xyz";
  char *dup = strdup( str );
  char **output = malloc( 5 * sizeof(char *) );
  char *p = dup;
  char *nextp = NULL;
  int i = 0;

  if( dup == NULL ) {
    // handle error
  }

  for( i = 0; i < 5; ++i ) {
    output[i] = strtok_r( p, " ", &nextp );
    p = NULL;
  }

  for( i = 0; i < 5; ++i ) {
    printf( "output[%d] = %s\n", i, output[i] );
  }

  free( dup );
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • `strtok_r`在Posix中. (3认同)