如何将字符串分割到C 2串 [英] How to split a string to 2 strings in C

查看:131
本文介绍了如何将字符串分割到C 2串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道你如何能1串,它用分隔符分成2,如空间,以及2份分配到2个独立的字符串。我已经使用的strtok(),但无济于事尝试。


解决方案

 的#include<&string.h中GT;字符*记号。
焦线[] =几个字
字符*搜索=;
//令牌将指向数。
令牌= strtok的(行,搜索);
//令牌将指向字。
令牌= strtok的(NULL,搜索);


更新

请注意,在某些操作系统, strtok的手册页提到:


  

此接口由strsep废弃(3)。


用一个例子 strsep 如下:

 的char *记号。
字符*串;
字符* tofree;字符串的strdup =(ABC,DEF,GHI);如果(字符串!= NULL){  tofree =串;  而((令牌= strsep(安培;!串,,))= NULL)
  {
    的printf(%S \\ N标记);
  }  免费(tofree);
}

I was wondering how you could take 1 string, split it into 2 with a delimiter, such as space, and assign the 2 parts to 2 separate strings. I've tried using strtok() but to no avail.

解决方案

#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";


// Token will point to "SEVERAL".
token = strtok(line, search);


// Token will point to "WORDS".
token = strtok(NULL, search);


Update

Note that on some operating systems, strtok man page mentions:

This interface is obsoleted by strsep(3).

An example with strsep is shown below:

char* token;
char* string;
char* tofree;

string = strdup("abc,def,ghi");

if (string != NULL) {

  tofree = string;

  while ((token = strsep(&string, ",")) != NULL)
  {
    printf("%s\n", token);
  }

  free(tofree);
}

这篇关于如何将字符串分割到C 2串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆