我想从一个字符中删除字符串的一部分,即:
源字符串:
目标字符串:
源字符串:
manchester united (with nice players)
目标字符串:
manchester united
有多种方法可以实现。如果您拥有要替换的字符串,可以使用String
类的replace
或replaceAll
方法。如果您想要替换一个子字符串,可以使用substring
API获取子字符串。
例如:
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
要替换括号内的内容,您可以使用:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String toBeReplaced = str.substring(startIndex, endIndex + 1);
- Yeung字符串替换
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
编辑:
按索引
s = s.substring(0, s.indexOf("(") - 1);
s = s.replace(...)
的意思是要对字符串s执行替换操作,并将结果赋值回原变量s。请注意,原始字符串s本身不会被更改,而是创建并返回一个新的字符串对象。 - Sergey Kalinichenko使用 String.Replace() 方法:
http://www.daniweb.com/software-development/java/threads/73139
示例:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst()
可以被 replaceAll()
替换。
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
首先,我会使用标记“(”将原始字符串拆分为字符串数组,输出数组中的位置0的字符串就是您想要的内容。
String[] output = originalString.split(" (");
String result = output[0];
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
如果源字符串为null,则返回null。如果源字符串为空(""),则返回空字符串。如果要删除的字符串为null,则返回源字符串。如果要删除的字符串为空(""),则返回源字符串。
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
StringUtils.substringBefore(str, "(");
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
要去除末尾的空格,请使用str.trim()
Apache StringUtils函数可以处理null、空字符串和无匹配项的情况。
如果您要从末尾删除特定字符串,请使用 removeSuffix
(文档)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
如果要在某个字符后面删除,请使用
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
removePrefix
、removeRange
、removeSurrounding
和replaceAfterLast
。