char*到std::string的子字符串
Substring of char* to std::string
我有一个char
s数组,我需要提取该数组的子集并将它们存储在std::string
s中。我试图将数组分成行,基于找到n
字符。解决这个问题的最佳方法是什么?
int size = 4096;
char* buffer = new char[size];
// ...Array gets filled
std::string line;
// Find the chars up to the next newline, and store them in "line"
ProcessLine(line);
可能需要这样的接口:
std::string line = GetSubstring(char* src, int begin, int end);
我将创建std::string
作为第一步,因为拆分结果将容易得多。
int size = 4096;
char* buffer = new char[size];
// ... Array gets filled
// make sure it's null-terminated
std::string lines(buffer);
// Tokenize on 'n' and process individually
std::istringstream split(lines);
for (std::string line; std::getline(split, line, 'n'); ) {
ProcessLine(line);
}
您可以使用std::string(const char *s, size_t n)
构造函数从C字符串的子字符串构建std::string
。传入的指针可以指向C字符串的中间;不需要是第一个字符
如果你需要更多的信息,请更新你的问题,详细说明你的绊脚石在哪里
我没有意识到您只希望一次处理每行,但是如果您需要一次处理所有行,您也可以这样做:
std::vector<std::string> lines;
char *s = buffer;
char *head = s;
while (*s) {
if (*s == 'n') { // Line break found
*s = ' '; // Change it to a null character
lines.push_back(head); // Add this line to our vector
head = ++s;
} else s++; //
}
lines.push_back(head); // Add the last line
std::vector<std::string>::iterator it;
for (it = lines.begin(); it != lines.end(); it++) {
// You can process each line here if you want
ProcessLine(*it);
}
// Or you can process all the lines in a separate function:
ProcessLines(lines);
// Cleanup
lines.erase(lines.begin(), lines.end());
我已经修改了缓冲区,vector.push_back()方法从每个结果C子字符串自动生成std::string对象。
您的最佳选择(最佳含义最简单)是使用strtok
并通过构造函数将令牌转换为std::string
。(请注意,纯strtok
是不可重入的,因此您需要使用非标准的strtok_r
)。
void ProcessTextBlock(char* str)
{
std::vector<std::string> v;
char* tok = strtok(str,"n");
while(tok != NULL)
{
ProcessLine(std::string(tok));
tok = strtok(tok,"n");
}
}
可以使用std::string的构造函数将char*的子字符串转换为std::string:
template< class InputIterator >
basic_string( InputIterator first, InputIterator last, const Allocator& alloc = Allocator() );
就像这样做:
char *cstr = "abcd";
std::string str(cstr + 1, cstr + 3);
在这种情况下,str将是"bc"
相关文章:
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 将向量解析<string>为字符串
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- 将 std::string( "x3BxDEx7C" ) 转换为可读的十六进制字符串?
- 为什么 string::begin() 在即时窗口中输出整个字符串
- 比较 std::string 和 C 样式字符串文字
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- 将 c 字符串直接写入 std::string
- std::hash<std::string> 可以为不同的字符串返回相同的值吗?
- 反转没有循环的字符串,C++中只有 std::string 成员
- 为什么我不必从 std::string 的函数中释放字符串c_str?
- 包括<字符串>,使用不完整的类型"std::string"
- 如何找到串联ASCII和std::string的子字符串
- 如何在c++中打印原始std::string/c样式的字符串
- 从映射<字符串、矢量中对唯一值进行排序<string>>
- C++ 在列表变量名称中查找字符串字符串<string>