C++中使用replace函数实现字符串数字排序替换的问题
问题分析与修复
你的代码核心问题在于对string::replace函数的使用错误,以及循环逻辑混乱,下面逐一拆解并给出修复方案:
代码中的错误点
- 赋值而非判断:
if (i = 0)是赋值操作,不是相等判断,应当写成if (i == 0),且这个分支完全多余。 - replace参数错误:
string::replace的第一个参数是要替换的起始索引位置,你传入的original[i]是字符的ASCII值(比如'3'对应51),这会导致访问超出字符串范围的位置,触发未定义行为。 - 索引越界风险:当
i=0时,temp[i-1]会访问temp[-1],直接造成越界。 - 替换逻辑混乱:没有正确对应原字符串中每个数字的位置和排序后
temp中的字符。
修复方案:直接构建新字符串
没必要修改原字符串,用排序后的数字和分隔符直接构建结果更高效清晰:
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string original, temp; cin >> original; // 提取数字并排序 for (char c : original) { if (c != '+') { temp.push_back(c); } } sort(temp.begin(), temp.end()); // 构建结果字符串 string result; for (int i = 0; i < temp.size(); ++i) { result += temp[i]; if (i != temp.size() - 1) { // 最后一个数字后不加+ result += '+'; } } cout << result << endl; return 0; }
基于原字符串修改的修复版本
如果一定要修改原字符串,需要遍历原字符串,遇到数字时依次取排序后temp中的字符替换:
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string original, temp; cin >> original; // 提取数字并排序 for (char c : original) { if (c != '+') { temp.push_back(c); } } sort(temp.begin(), temp.end()); // 替换原字符串中的数字 int temp_idx = 0; // 跟踪排序后数字的位置 for (int i = 0; i < original.size(); ++i) { if (original[i] != '+') { // 直接赋值字符比调用replace更高效 original[i] = temp[temp_idx++]; } } cout << original << endl; return 0; }
说明
- 用
temp_idx跟踪排序后数字的位置,每次遇到原字符串中的数字,就用temp[temp_idx]替换,随后temp_idx自增。 - 直接对
original[i]赋值字符,比调用replace函数更简洁高效。
内容的提问来源于stack exchange,提问作者user26134900
相关产品推荐
相关产品推荐

