如何在函数中迭代 std::string const& ?

问题描述 投票:0回答:1

我将 const 引用 std::string 传递给函数。我想迭代字符串的三元组并将这些三元组转换为整数。我通过位移来做到这一点。我的问题是我不知道如何迭代字符串,因为我需要字符串中三元组的元素和索引。

#include <vector>
#include <string>

unsigned int three_char_to_int(std::string start){
    unsigned int substr {0};

    substr |= start[0];
    substr |= (start[1] << 8);
    substr |= (start[2] << 16);

    return substr;
}

std::vector<int> test_Function(std::string const& text){

    int length = text.length();

    std::vector<unsigned int> res = std::vector<unsigned int>(length, 0);

    for(int i {0}; i < length-2; ++i){
        continue;

        // text is not a pointer, so this does not work
        // res[i] = three_char_to_int(text +i);

        // this does not work either
        // res[i] = three_char_to_int(text[i]);
    }

}

int main(){

    std::string text = {"Hello, World!"};
    auto result = test_Function(text);

    // do something with result

    return 0;
} 

如果有任何提示和解决方案,我将不胜感激。如果您有更好的想法如何做我正在尝试的事情,我也会很高兴看到。

注意:我正在学习C++

c++ std stdstring
1个回答
0
投票

假设您不尝试使用 c++20 功能,请尝试利用

std::vector::emplace_back
std::string::substr

#include <iostream>
#include <string>
#include <vector>

/**
 * @brief Converts a 3-character string to an unsigned int.
 *
 * @param start The string to be converted, must be at least 3 characters long.
 * @return unsigned int The resulting unsigned int from the conversion.
 */
unsigned int three_char_to_int(const std::string& start) {
  unsigned int substr = 0;
  substr |= static_cast<unsigned char>(start[0]);
  substr |= static_cast<unsigned char>(start[1]) << 8;
  substr |= static_cast<unsigned char>(start[2]) << 16;
  return substr;
}

/**
 * @brief Processes a string to convert each consecutive triple of characters into an unsigned int.
 *
 * @param text The const reference to the input string to be processed.
 * @return std::vector<unsigned int> A vector containing the converted unsigned ints.
 */
std::vector<unsigned int> test_Function(const std::string& text) {
  std::vector<unsigned int> res;
  res.reserve(text.length() - 2); // Code go brrr 🏎️...
  for (size_t i = 0; i + 2 < text.length(); ++i) {
    res.emplace_back(three_char_to_int(text.substr(i, 3)));
  }
  return res;
}

int main() {
  std::string text = "Hello, World!";
  std::vector<unsigned int> result = test_Function(text);
  for (auto &i : result) {
    std::cout << i << '\n';
  }
  return 0;
}

输出:

7103816
7105637
7302252
2912108
2108527
5709868
7296800
7499607
7107183
6581362
2188396
© www.soinside.com 2019 - 2024. All rights reserved.