如何截断字符串数组?C++

How to truncate a string array? C++

本文关键字:C++ 数组 字符串 何截断      更新时间:2023-10-16

假设我有一个包含 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;
});