替换字符串中的一些字符 [英] Replace some character in string

查看:155
本文介绍了替换字符串中的一些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个8个字符的字符串'00001111'我想替换一些特定的索引值。例如,如果我检查 stringName [2] =='0'并使用 stringName.replace(2,2, 1)那么它替换,但一个字符在末尾错过

I have a string of 8 characters '00001111' I want to replace some specific index value. For example if I check stringName[2]=='0' and replce it using stringName.replace(2,2,"1") then it replaces but one character is missed at the end

if (xyz[3]=='0')
{
    xyz.replace(3,3,"1");
}
else
{
    xyz.replace(3, 3, "0");
}

推荐答案

问题是替换方法的误用,第一个参数是index的替换开始,第二个是长度,第三个是应该插入的字符串。因此,替换(2,2,0)意味着用0(一个字符串的字符串)替换从索引2开始的两个字符,这就是为什么字符消失的原因。

The problem is misuse of the replace method, the first parameter is index of the start for replace, the second is length, and the third is the string that should be inserted. hence saying replace(2,2,"0") means replace the two chars that start at index 2 with "0" (a string of one char), that is why you have chars disappearing.

解决方案就像人们说的,string [index_you_want_to_replace] ='some_char'。

the solution is as people said, string[index_you_want_to_replace] = 'some_char'.

这篇关于替换字符串中的一些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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