如何从字符串中删除单个字符 [英] How to remove single character from a String
本文介绍了如何从字符串中删除单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了在 Java 中访问字符串的单个字符,我们有 String.charAt(2)
.java中是否有任何内置函数可以删除字符串的单个字符?
For accessing individual characters of a String in Java, we have String.charAt(2)
. Is there any inbuilt function to remove an individual character of a String in java?
像这样:
if(String.charAt(1) == String.charAt(2){
//I want to remove the individual character at index 2.
}
推荐答案
您也可以使用可变的 StringBuilder
类.
You can also use the StringBuilder
class which is mutable.
StringBuilder sb = new StringBuilder(inputString);
它有方法 deleteCharAt()
,以及许多其他的mutator方法.
It has the method deleteCharAt()
, along with many other mutator methods.
只需删除需要删除的字符,然后得到如下结果:
Just delete the characters that you need to delete and then get the result as follows:
String resultString = sb.toString();
这避免了创建不必要的字符串对象.
This avoids creation of unnecessary string objects.
这篇关于如何从字符串中删除单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文