如何截断字符串数组?C++
How to truncate a string array? C++
假设我有一个包含 5 个单词的字符串数组,我只想输出每个单词的前 3 个字母。我该怎么做?我知道如何使用一个字符串来做到这一点,但是对于一个字符串数组,我会迷路。
这是用一个字符串做到这一点的方法
std::string test = "hello";
std::cout << test << std::endl;
test = test.substr(0,3);
std::cout << test << std::endl;
我想做的是这个
std::string test[5] = {"hello", "pumpkin", "friday", "snowboard", "snacks"};
我想找出每个单词的前 3 个字母。我试过测试[5] = 测试[5].substr(0,3(;这行不通。
test[5] 不起作用,因为数组中只有 5 个项目,只有索引 0 到 4 有效。
通常对于数组,您需要编写一个循环来依次遍历每个数组项,例如
for (int i = 0; i < 5; ++i)
test[i] = test[i].substr(0,3);
for (int i = 0; i < 5; ++i)
cout << test[i] << endl;
有了test[5]
,你就是在越界读取,从而调用未定义的行为。C++中的数组索引为零,因此最后一个元素将test[4]
。创建一个函数,例如使用 std::next 函数或字符串的 substr 成员函数。在基于范围的循环内调用:
#include <iostream>
#include <string>
void foo(const std::string& s) {
if (s.size() >= 3) {
std::cout << std::string(s.begin(), std::next(s.begin(), 3)) << 'n';
// or simply:
std::cout << s.substr(0, 3) << 'n';
}
}
int main() {
std::string test[5] = { "hello", "pumpkin", "friday", "snowboard", "snacks" };
for (const auto& el : test) {
foo(el);
}
}
test[5] = test[5].substr(0,3); won't work and more over you don't have `test[5]`, index starts from `0`.
你可能想这样做
for(int i=0 ; i<5; i++) {
test[i] = test[i].substr(0,3);
cout << test[i] << endl;
}
substr
就是您要找的。这是我的实现。
#include <array>
#include <string>
#include <iostream>
int main () {
std::array<std::string,5> list {"hello", "pumpkin", "friday", "snowboard", "snacks"};
for (const auto &word : list){
std::cout << word << std::endl;
}
for (auto &word : list){
word = word.substr(0,3);
}
for (const auto &word : list){
std::cout << word << std::endl;
}
}
使用标准库。
std::for_each(std::begin(test), std::end(test), [] (auto& s) { s.erase(3); });
甚至是一个简单的基于范围的 for 循环:
for (auto&& s : test) {
s.erase(3); // Erase from index 3 to end of string.
}
或者甚至可以创建另一个包含原始字符串视图的容器:
auto test2 = std::accumulate(std::begin(test), std::end(test),
std::vector<std::string_view>{},
[] (auto& prev, std::string_view sv) -> decltype(prev)& {
prev.push_back(sv.substr(0, 3));
return prev;
});
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '