我试图仅替换字符串 dart 中的一个字符,但找不到任何有效的方法。由于字符串不是 Dart 中的数组,我无法通过索引直接访问字符,并且没有内置函数可以做到这一点。这样做的有效方法是什么?
目前我正在这样做,如下所示:
List<String> bedStatus = currentBedStatus.split("");
bedStatus[index]='1';
String bedStatusFinal="";
for(int i=0;i<bedStatus.length;i++){
bedStatusFinal+=bedStatus[i];
}
}
索引是一个int and 当前床位状态 is the string我正在尝试操纵。
替换特定索引:
As String
在飞镖中是不可变的 refer https://api.dartlang.org/stable/2.0.0/dart-core/String-class.html,我们无法编辑类似的内容
stringInstance.setCharAt(index, newChar)
高效的方式满足要求将是:
String hello = "hello";
String hEllo = hello.substring(0, 1) + "E" + hello.substring(2);
print(hEllo); // prints hEllo
搬进一个function:
String replaceCharAt(String oldString, int index, String newChar) {
return oldString.substring(0, index) + newChar + oldString.substring(index + 1);
}
replaceCharAt("hello", 1, "E") //usage
Note: index
在上面的函数中是零基础.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)