C ++,在特定索引处更改字符串的最佳方法 [英] C++, best way to change a string at a particular index

查看:64
本文介绍了C ++,在特定索引处更改字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这样的特定索引处更改C ++字符串:

I want to change a C++ string at a particular index like this:

string s = "abc";
s[1] = 'a';

以下代码有效吗?这是可以接受的方法吗?

Is the following code valid? Is this an acceptable way to do this?

我没有找到任何有效的参考文献:

I didn't find any reference which says it is valid:

http://www.cplusplus.com/reference/string/string/

其中说,通过字符串中的[]重载[]运算符",我们可以执行写操作.

Which says that through "overloaded [] operator in string" we can perform the write operation.

推荐答案

在索引处将字符分配给 std :: string 会产生正确的结果,例如:

Assigning a character to an std::string at an index will produce the correct result, for example:

#include <iostream>
int main() {
    std::string s = "abc";
    s[1] = 'a';
    std::cout << s;
}

会打印 aac .缺点是,如果字符串s为blankstring或写得太远,则可能会意外写入未分配的内存.C ++很乐意注销掉字符串的结尾,这会导致未定义的行为.

which prints aac. The drawback is you risk accidentally writing to un-assigned memory if string s is blankstring or you write too far. C++ will gladly write off the end of the string, and that causes undefined behavior.

一种更安全的方法是使用 string :: replace :

A safer way to do this would be to use string::replace: http://cplusplus.com/reference/string/string/replace

例如

#include <iostream> 
int main() { 
    std::string s = "What kind of king do you think you'll be?"; 
    std::string s2 = "A good king?"; 
    //       pos len str_repl 
    s.replace(40, 1, s2); 
    std::cout << s;   
    //prints: What kind of king do you think you'll beA good king?
}

replace函数采用字符串s,并在位置40处用字符串s2替换一个字符,即问号.如果字符串为空或您分配了超出范围的内容,则没有未定义的行为.

The replace function takes the string s, and at position 40, replaced one character, a questionmark, with the string s2. If the string is blank or you assign something out of bounds, then there's no undefined behavior.

这篇关于C ++,在特定索引处更改字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆