我想从一个字符中删除一部分字符串,即:
源字符串:
manchester united (with nice players)
Run Code Online (Sandbox Code Playgroud)
目标字符串:
manchester united
Run Code Online (Sandbox Code Playgroud)
mpr*_*hat 144
有多种方法可以做到这一点.如果您有要替换的字符串,则可以使用该类的replace或replaceAll方法String.如果您要替换子字符串,可以使用substringAPI 获取子字符串.
例如
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));
Run Code Online (Sandbox Code Playgroud)
要替换"()"中的内容,您可以使用:
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));
Run Code Online (Sandbox Code Playgroud)
Sha*_*nas 28
字符串替换
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Run Code Online (Sandbox Code Playgroud)
编辑:
按索引
s = s.substring(0, s.indexOf("(") - 1);
Run Code Online (Sandbox Code Playgroud)
Mat*_*att 18
使用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)","");
Run Code Online (Sandbox Code Playgroud)
我首先将原始字符串拆分为带有标记"("的String数组,并且输出数组的位置0处的String是您想要的.
String[] output = originalString.split(" (");
String result = output[0];
Run Code Online (Sandbox Code Playgroud)
小智 6
使用StringBuilder,您可以替换以下方式.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
Run Code Online (Sandbox Code Playgroud)
originalString.replaceFirst("[(].*?[)]", "");
Run Code Online (Sandbox Code Playgroud)
https://ideone.com/jsZhSC
replaceFirst()可以替换为replaceAll()
小智 5
您应该使用String对象的substring()方法.
这是一个示例代码:
假设:我在这里假设您要检索字符串直到第一个括号
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);
Run Code Online (Sandbox Code Playgroud)