使用单个区别符分开字符串
Splitting a string using a single delimeter
可能的重复:
中拆分字符串
在C
我正在尝试将带有分配器的单个字符串对象分为单独的字符串,然后输出单个字符串。
例如,输入字符串是firstName,lastname-age-cuputation-telephone
' - '字符是特定器,我需要仅使用字符串类函数分别输出它们。
最好的方法是什么?我很难理解。substr和类似功能。
谢谢!
我认为字符串流和 getline
可以易于阅读代码:
#include <string>
#include <sstream>
#include <iostream>
std::string s = "firstname,lastname-age-occupation-telephone";
std::istringstream iss(s);
for (std::string item; std::getline(iss, item, '-'); )
{
std::cout << "Found token: " << item << std::endl;
}
这仅使用string
成员函数:
for (std::string::size_type pos, cur = 0;
(pos = s.find('-', cur)) != s.npos || cur != s.npos; cur = pos)
{
std::cout << "Found token: " << s.substr(cur, pos - cur) << std::endl;
if (pos != s.npos) ++pos; // gobble up the delimiter
}
我会做这样的事情
do
{
std::string::size_type posEnd = myString.find(delim);
//your first token is [0, posEnd). Do whatever you want with it.
//e.g. if you want to get it as a string, use
//myString.substr(0, posEnd - pos);
myString = substr(posEnd);
}while(posEnd != std::string::npos);
相关文章:
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 这两个C++语句连接字符串有什么区别?
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 使用短运算符的字符串连接有区别吗?
- 在 C++ 中,字符串 a= "hello" 和字符串 a=(char *) "hello"有什么区别?
- cin>>gender 和 cin>>*gender ( c 样式文本字符串)有什么区别
- C++ 字符串追加和运算符 += 之间的区别
- Boost.Hana JSON 示例:字符串和 decltype(std::to_string(..))之间的区别
- 字符串 += s1 和字符串 = 字符串 + s1 之间的区别
- 结构产生的字符串有什么区别
- STD :: cin和Scanf()应用于字符串之间的区别
- C++ 和 pascal 字符串之间的区别
- 在 C++ 中,字符串的这两种不同初始化有什么区别?
- 初始化空字符串的 " " 和 {} 有什么区别?
- c++ 中字符串 s=s+"0" 和 s+="0" 之间的区别
- 字符串和向量<string>元素之间的区别
- 字符文字与字符串字面的u前缀有什么区别
- 使用单个区别符分开字符串
- 空字符串和"\0"字符有什么区别?(从指针和数组的角度来看)