简体   繁体   English

使用at函数替换字符串中的字符?

[英]replace a character in a string using at function?

I have a string CorrAns = "Text", I want to replace a character at a particular position with a character from another string. 我有一个字符串CorrAns =“ Text”,我想用另一个字符串中的字符替换特定位置的字符。 I used the following: 我使用了以下内容:

CorrAns.replace(1,1,OtherString.at(pos));

But its giving error, what is the best way to do this?? 但是它给与错误,最好的方法是什么?

Just use at (or the [] operator) accross the board: 只要使用at (或者[]操作者)进行的跨板:

corrAns[1] = otherString[pos];

(Note that at rarely has the semantics you want. If a bounds error is a precondition failure, as is usually the case, the last thing you want is an exception.) (请注意, at很少有你想要的语义。如果一个边界错误是一个前提条件故障,通常情况下,你想的最后一件事是个例外。)

Your syntax is wrong. 您的语法错误。 There are several methods for replace() function. replace()函数有几种方法。 Check below : 检查以下:

http://www.ansatt.hig.no/frodeh/ooprog/string2.html http://www.ansatt.hig.no/frodeh/ooprog/string2.html

replace has no overload taking size, size, char . replace没有重载,它的size, size, char You want 你要

CorrAns.replace(1, 1, 1, OtherString.at(pos));

or 要么

CorrAns.replace(1, 1, OtherString.substr(pos, 1));

The straightforward way to do this would be: 做到这一点的直接方法是:

CorrAns[1] = OtherString[pos];

If you insist on using the replace function, check out this reference . 如果您坚持使用replace功能,请查阅此参考资料 One correct call would look like: 一个正确的呼叫将如下所示:

CorrAns.replace(1, 1, 1, OtherString.at(pos));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM