有一个简单的方法来删除子字符串从给定的字符串在Java?
例如:“Hello World!”,去掉“o”→“Hell Wrld!”
有一个简单的方法来删除子字符串从给定的字符串在Java?
例如:“Hello World!”,去掉“o”→“Hell Wrld!”
当前回答
除了@DwB answer,你还可以使用StringUtils remove:
String hello = "hello world";
String hellYeah = StringUtils.remove(hello, "o");
或removeIgnoreCase:
String hello = "hellO world";
String hellYeah = StringUtils.remove(hello, "o");
其他回答
你也可以使用番石榴的CharMatcher。removeFrom函数。
例子:
String s = CharMatcher.is('a').removeFrom("bazaar");
下面是从给定字符串中删除所有子字符串的实现
public static String deleteAll(String str, String pattern)
{
for(int index = isSubstring(str, pattern); index != -1; index = isSubstring(str, pattern))
str = deleteSubstring(str, pattern, index);
return str;
}
public static String deleteSubstring(String str, String pattern, int index)
{
int start_index = index;
int end_index = start_index + pattern.length() - 1;
int dest_index = 0;
char[] result = new char[str.length()];
for(int i = 0; i< str.length() - 1; i++)
if(i < start_index || i > end_index)
result[dest_index++] = str.charAt(i);
return new String(result, 0, dest_index + 1);
}
isSubstring()方法的实现在这里
你应该看看StringBuilder/StringBuffer,它允许你删除,插入,替换指定偏移量的字符。
除了@DwB answer,你还可以使用StringUtils remove:
String hello = "hello world";
String hellYeah = StringUtils.remove(hello, "o");
或removeIgnoreCase:
String hello = "hellO world";
String hellYeah = StringUtils.remove(hello, "o");
你可以使用StringBuffer
StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);