简体   繁体   English

在 Java 中删除部分字符串

[英]Remove part of string in Java

I want to remove a part of string from one character, that is:我想从一个字符中删除一部分字符串,即:

Source string:源字符串:

manchester united (with nice players)

Target string:目标字符串:

manchester united

There are multiple ways to do it.有多种方法可以做到。 If you have the string which you want to replace you can use the replace or replaceAll methods of the String class.如果您有要替换的字符串,可以使用String类的replacereplaceAll方法。 If you are looking to replace a substring you can get the substring using the substring API.如果您要替换子字符串,您可以使用substring API 获取子substring

For example例如

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

To replace content within "()" you can use:要替换“()”中的内容,您可以使用:

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 Replace字符串替换

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

Edit:编辑:

By Index按索引

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

Use String.Replace():使用 String.Replace():

http://www.daniweb.com/software-development/java/threads/73139 http://www.daniweb.com/software-development/java/threads/73139

Example:例子:

String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");

https://ideone.com/jsZhSC https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll() replaceFirst()可以替换为replaceAll()

Using StringBuilder , you can replace the following way.使用StringBuilder ,您可以通过以下方式替换。

StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");

You should use the substring() method of String object.您应该使用 String 对象的 substring() 方法。

Here is an example code:这是一个示例代码:

Assumption: I am assuming here that you want to retrieve the string till the first parenthesis假设:我在这里假设您要检索字符串直到第一个括号

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

I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.我首先将原始字符串拆分为一个带有标记“(”的字符串数组,输出数组位置 0 处的字符串是您想要的。

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

String result = output[0];

Using StringUtils from commons lang使用 commons lang 中的 StringUtils

A null source string will return null.空源字符串将返回空值。 An empty ("") source string will return the empty string.空 ("") 源字符串将返回空字符串。 A null remove string will return the source string.空删除字符串将返回源字符串。 An empty ("") remove string will return the source string.空 ("") 删除字符串将返回源字符串。

String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
// 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);

    }
}

If you just need to remove everything after the "(", try this. Does nothing if no parentheses.如果您只需要删除“(”之后的所有内容,请尝试此操作。如果没有括号,则不执行任何操作。

StringUtils.substringBefore(str, "(");

If there may be content after the end parentheses, try this.如果结束括号后可能有内容,请尝试此操作。

String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")"); 

To remove end spaces, use str.trim()要删除结尾空格,请使用str.trim()

Apache StringUtils functions are null-, empty-, and no match- safe Apache StringUtils函数是空、空和无匹配安全的

Kotlin Solution科特林解决方案

If you are removing a specific string from the end, use removeSuffix ( Documentation )如果要从末尾删除特定字符串,请使用removeSuffix文档

var text = "one(two"
text = text.removeSuffix("(two") // "one"

If the suffix does not exist in the string, it just returns the original如果字符串中不存在后缀,则只返回原来的

var text = "one(three"
text = text.removeSuffix("(two") // "one(three"

If you want to remove after a character, use如果要删除字符后,请使用

// 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, "")

You can also check out removePrefix , removeRange , removeSurrounding , and replaceAfterLast which are similar您还可以查看removePrefixremoveRangeremoveSurroundingreplaceAfterLast

The Full List is here: ( Documentation )完整列表在这里:( 文档

You could use replace to fix your string.您可以使用replace来修复您的字符串。 The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.以下将返回“(”之前的所有内容,并删除所有前导和尾随空格。如果字符串以“(”开头,它将保持原样。

str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM