为多种类型标记字符串
Tokenizing a String for Multiple Types
我已经习惯了使用一个函数,在C++中,它解析一个字符串/缓冲区,由特定字符分隔,并将其中一个标记分配给通过引用传入的值,并返回缓冲区/字符串的其余部分。 然而,我的记忆在工作方式上有点错误,而且我在尝试重新创建它时遇到了一些困难。
我想知道是否有可能通过巧妙地使用模板函数来做到这一点,因为我并不完全熟悉模板函数的用法。
我的目标是
大致如下:// assume buffer is a string, delimited by some character, say '^'
// in this particular scenario: 5^3.14^test^
TokenAssignment( buffer, testInt );
TokenAssignment( buffer, testFloat );
TokenAssignment( buffer, testString );
template<class Token>
void TokenAssignment(std::string& buffer, Token& tokenToBeAssigned)
{
std::string::size_type offset = buffer.find_first_of ('^');
/* Logic here assigns token to the value in the string regardless of type. */
// move the buffer on
buffer = buffer.substr(offset+1);
}
// so the three calls above would have
// testInt = 5
// testFloat = 3.14f
// testString = "test"
这样的事情可能吗?
你似乎已经把第一部分放下来了,把字符串分成更小的字符串("5"、"3.14"、"test")。
将这些值分配给其他类型的变量(例如 "3.14" => 3.14
),stringstream
非常方便:
#include <sstream>
template<typename T>
void scanString(std::string str, T &x)
{
std::stringstream ss;
ss << str;
ss >> x;
}
相关文章:
- 如何检查模板类中的变量是否为字符串类型?
- C++类字符串类型的迭代器
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 字符串类型的 2d 数组(C++;)
- 在 Rcpp 中的字符串类型之间转换时出错
- 为什么字符串类型会导致 c++ 程序无法运行?
- 如何将字符串类型转换为 ostringstream
- 当正斜杠运算符应用于C++中的字符串类型时,它会做什么
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 我在 c++ 中声明字符串类型时遇到问题
- 对齐C++字符串类型问题 std::字符串到 TStr
- C++无符号字符串类型的正则表达式
- 当 JSON 值应为 INT 但以字符串类型发送时,RapidJSON 崩溃
- 如何使用 std::find 从向量的第一个元素中查找字符串<字符串对<字符串、字符串> >类型?
- 我想添加两个字符串类型的矩阵.用户将不会输入行数或列的数量.用户将仅输入数组
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何根据定义的字符串类型在“std::cout”和“std::wcout”之间进行选择
- C++ 仅当模板为字符串类型时执行小写转换
- 字符串类型的 C++ 模板无法编译
- 如何使用新字符串而不是分配器创建自己的字符串类型向量?