1.题目
问题描述
给定一个字符串ss,编写一个函数,将字符串中的小写字母a替换为"%100",并返回替换后的字符串。
例如,对于字符串"abcdwa",所有a字符会被替换为"%100",最终结果为%100bcdw%100"。
测试样例
样例1:
输入:s = "abcdwa"
输出:
'%100bcdw%100'
样例2:
输入:s = "banana"
输出:
'b%100n%100n%100'
样例3:
输入:s = "apple"
输出:
'%100pple'
2.思路
字符串替换
string replace (size_t pos, size_t len, const string& str);
其中,pos表示要替换的子串在原字符串中的起始位置,len表示要替换的子串的长度,str表示用来替换的字符串。
替换会更改原字符串,可以定义一个新的字符串,遇到a,就追加%100,遇到别的字符,追加原字符
3.代码
#include <iostream>
#include <string>
using namespace std;
std::string solution(const std::string& s) {
// write code here
string new_s = "";
for (int i = 0;i<s.size();i++){
if(s[i] == 'a'){
new_s += "%100";
}else{
new_s += s[i];
}
}
return news_s; // Placeholder
}
int main() {
std::cout << (solution("abcdwa") == (%100bcdw%100") << std::endl;
std::cout << (solution("banana") == "b%100n%100n%100") << std::endl;
std::cout << (solution("apple") == (%100pple") << std::endl;
return 0;
}