删除部分string

我想从一个字符中删除一部分string,即:

原始string:曼彻斯特联合(与好的球员)

未来的结果:曼彻斯特联合

有多种方法可以做到这一点。 如果您有要replace的string,则可以使用String类的replacereplaceAll方法。 如果您正在寻找replace子string,您可以使用substring API获取子substring

例如

 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)); 

要replace“()”中的内容,您可以使用:

 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)); 

stringreplace

 String s = "manchester united (with nice players)"; s = s.replace(" (with nice players)", ""); 

编辑:

按索引

 s = s.substring(0, s.indexOf("(") - 1); 

使用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)",""); 

我将首先将原始string拆分为一个string数组与一个标记“(”和输出数组的位置0的string是你想要的。

 String[] output = originalString.split(" ("); String result = output[0]; 

你应该使用String对象的substring()方法。

这是一个示例代码:

假设:我在这里假设你想要检索string,直到第一个括号

 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); 

使用StringBuilder ,你可以replace下面的方法。

 StringBuilder str = new StringBuilder("manchester united (with nice players)"); int startIdx = str.indexOf("("); int endIdx = str.indexOf(")"); str.replace(++startIdx, endIdx, ""); 
 originalString.replaceFirst("[(].*?[)]", ""); 

https://ideone.com/jsZhSC
replaceFirst()可以replace为replaceAll()

你可以使用replace来修复你的string。 下面的代码将返回“(”之前的所有内容,同时也删除所有前导和尾随的空白。如果string以“(”开头,则它将保持原样。

 str = "manchester united (with nice players)" matched = str.match(/.*(?=\()/) str.replace(matched[0].strip) if matched 
 // Java program to remove a substring from a string public class RemoveSubString { public static void main(String[] args) { String master = "1,2,3,4,5"; String to_remove="3,"; String new_string = master.replace(to_remove, ""); // the above line replaces the t_remove string with blank string in master System.out.println(master); System.out.println(new_string); } }