用std :: string中字母表中的每個字符替換所有出現的字符的有效方法是什么?
##include <algorithm>
#include <string>
using namespace std;
void some_func() {
string s = "example *trin*";
string letters = "abcdefghijklmnopqrstuvwxyz";
// replace all '*' to 'letter of alphabet'
for (int i = 0; i < 25; i )
{
//replace letter * with a letter in string which is moved 1 each loop
replace(s.begin(), s.end(), '*', letters.at(i));
i ;
cout << s;
}
我怎樣才能讓它作業?
uj5u.com熱心網友回復:
你可以有一個功能:
- 接收要操作的字串,以及要替換的字符,以及
- 替換完成后,回傳包含新字串的串列;
- 對于字母表中的每個字母,您可以檢查它是否在輸入字串中,在這種情況下,創建輸入字串的副本,使用 進行替換
std::replace,并將其添加到回傳串列中。
[演示]
#include <algorithm> // replace
#include <fmt/ranges.h>
#include <string>
#include <string_view>
#include <vector>
std::vector<std::string> replace(const std::string& s, const char c) {
std::string_view alphabet{"abcdefghijklmnopqrstuvwxyz"};
std::vector<std::string> ret{};
for (const char l : alphabet) {
if (s.find(c) != std::string::npos) {
std::string t{s};
std::ranges::replace(t, c, l);
ret.emplace_back(std::move(t));
}
}
return ret;
}
int main() {
std::string s{"occurrences"};
fmt::print("Replace '{}': {}\n", 'c', replace(s, 'c'));
fmt::print("Replace '{}': {}\n", 'z', replace(s, 'z'));
}
// Outputs:
//
// Replace 'c': ["oaaurrenaes", "obburrenbes", "oddurrendes"...]
// Replace 'z': []
編輯:在下面更新您的評論。
但是,如果我想一次替換 1 個字符,例如出現多個“C”,如果我只想替換其中的 1 個,則運行所有結果,然后移動到下一個“C”并替換所有字符,然后等等,怎么可能呢?
在這種情況下,您需要遍歷輸入字串,一次替換一個字符,并將這些新字串中的每一個添加到回傳串列中。
[演示]
for (const char l : alphabet) {
if (s.find(c) != std::string::npos) {
for (size_t i{0}; i < s.size(); i) {
if (s[i] == c) {
std::string t{s};
t[i] = l;
ret.emplace_back(std::move(t));
}
}
}
}
// Outputs:
//
// Replace 'c': ["oacurrences", "ocaurrences", "occurrenaes"...]
// Replace 'z': []
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486133.html
上一篇:如何讀取檔案并將其寫入字串c
下一篇:用默認引數推導可變引數模板引數
