更改 ascii 代码并将字符添加到 C++ 中的字符串
change ascii code and preappend character to string in C++
我想在对字符 ascii 代码执行一些计算后将一个字符预先附加到字符串,但是 (somenumber+'0') + s
不起作用,我不明白为什么。
我想要的答案是 "ahello" 使用 ('0' + 49)
的 ascii 表示
这是我试过的:
std::string s = "hello";
s.insert(0, std::to_string('a'));
std::cout << s << std::endl; // 97hello
s = "hello";
s += 'a';
std::cout << s << std::endl; // helloa
s = "hello";
s = 'a' + s;
std::cout << s << std::endl; // ahello
//s = (49+'0') + s;
//std::cout << s << std::endl;
这将解决问题:
s.insert(0, string(1,1+'a'));
O/p
你好
s.insert(0, string(1,0+'a'));
O/P
你好
您要附加字符 (97) 的 ASCII 代码 int 还是要附加 ASCII 表示形式 ('a')?
后一种情况,直接使用s.insert(0, "a")
即可。
如果你想将之前的ASCII码转换为int,你可以使用std::string fill constructor,Steephen已经指出:
// fills the string with n consecutive copies of character c.
std::string(size_t n, char c);
// so you could do this to get a string "f":
std::string(1, 'a'+5);
尝试
s.insert(0, string(1,49+'a'));
我想在对字符 ascii 代码执行一些计算后将一个字符预先附加到字符串,但是 (somenumber+'0') + s
不起作用,我不明白为什么。
我想要的答案是 "ahello" 使用 ('0' + 49)
的 ascii 表示这是我试过的:
std::string s = "hello";
s.insert(0, std::to_string('a'));
std::cout << s << std::endl; // 97hello
s = "hello";
s += 'a';
std::cout << s << std::endl; // helloa
s = "hello";
s = 'a' + s;
std::cout << s << std::endl; // ahello
//s = (49+'0') + s;
//std::cout << s << std::endl;
这将解决问题:
s.insert(0, string(1,1+'a'));
O/p
你好
s.insert(0, string(1,0+'a'));
O/P
你好
您要附加字符 (97) 的 ASCII 代码 int 还是要附加 ASCII 表示形式 ('a')?
后一种情况,直接使用s.insert(0, "a")
即可。
如果你想将之前的ASCII码转换为int,你可以使用std::string fill constructor,Steephen已经指出:
// fills the string with n consecutive copies of character c.
std::string(size_t n, char c);
// so you could do this to get a string "f":
std::string(1, 'a'+5);
尝试
s.insert(0, string(1,49+'a'));