如何拆分vc ++中的字符串? [英] How to split the strings in vc++?

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

问题描述

我有一个字符串stack + ovrflow * newyork;我必须拆分这个堆栈,溢出,newyork

I have a string "stack+ovrflow*newyork;" i have to split this stack,overflow,newyork

任何想法

推荐答案

首先,如果可用,我总是使用boost :: tokenizer来执行这种任务(参见下面的优秀答案)。

First and foremost if available, I would always use boost::tokenizer for this kind of task (see and upvote the great answers below)

boost,你有几个选项:

Without access to boost, you have a couple of options:

您可以使用C ++ std :: strings并使用stringstream和getline(最安全的方式)解析它们

You can use C++ std::strings and parse them using a stringstream and getline (safest way)

std::string str = "stack+overflow*newyork;";
std::istringstream stream(str);
std::string tok1;
std::string tok2;
std::string tok3;

std::getline(stream, tok1, '+');
std::getline(stream, tok2, '*');
std::getline(stream, tok3, ';');

std::cout << tok1 << "," << tok2 << "," << tok3 << std::endl

或者你可以使用strtok家族的函数

Or you can use one of the strtok family of functions (see Naveen's answer for the unicode agnostic version; see xtofls comments below for warnings about thread safety), if you are comfortable with char pointers

char str[30]; 
strncpy(str, "stack+overflow*newyork;", 30);

// point to the delimeters
char* result1 = strtok(str, "+");
char* result2 = strtok(str, "*");
char* result3 = strtok(str, ";");

// replace these with commas
if (result1 != NULL)
{
   *result1 = ',';
}
if (result2 != NULL)
{
   *result2 = ',';
}

// output the result
printf(str);

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

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