简体   繁体   中英

Replace last part of string

I want to replace the last String which is a , with )

Suppose the string is:

Insert into dual (name,date,

to be converted to:

Insert into dual (name,date)

The following code should replace the last occurrence of a ',' with a ')' .

StringBuilder b = new StringBuilder(yourString);
b.replace(yourString.lastIndexOf(","), yourString.lastIndexOf(",") + 1, ")" );
yourString = b.toString();

Note This will throw Exceptions if the String doesn't contain a ',' .

You can use regular expression:

String aResult = "Insert into dual (name,date,".replaceAll(",$", ")");

replaceAll(...) will match string string with the given regular expression (parameter 1) (in this case we match the last character if it is a comma). The replace it with a replacement (parameter 2) (in this case is ' ) ').

If you want to ensure that tailing spaces and tabs are taken care of, you can just change the regex to ' ,\\[ \\t\\]*$ '. NOTE ' \\[ ' and ' \\] ' is without backslash (I don't know how to properly escape it).

Hope this helps.

This is a custom method to replace only the last substring of a given string. It would be useful for you:

private String replaceLast(String string, String from, String to) {
     int lastIndex = string.lastIndexOf(from);
     if (lastIndex < 0) return string;
     String tail = string.substring(lastIndex).replaceFirst(from, to);
     return string.substring(0, lastIndex) + tail;
}
str = str.substring(0, str.lastIndexOf(",")) + ")";

The more readable way ... Which you can use to learn about String and its' functions

String myString = "Insert into dual (name,date,";
String newString = "";
int length = myString.length();
String lastChar = myString.substring(length-1);

if (lastChar.contains(",")) {
    newString = myString.substring(0,length-1) + ")";
} 

System.out.println(newString);

Check the length of the string, check the last char (if you have the length it is easy) and replace it - when necessary. This solution is not lang. specific. just use a common sense.

Try this regex (^.+)b(.+$)

Example (Replace the last b character)

System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", "$1$2"));

TO replace a last char of your string by )

str = str.substring(0, str.length()-1)+")";

Make sure your string is not empty or null.

On a similar search I found this answer:

https://stackoverflow.com/a/37066403/875282

I think it is the best because it uses the java methods as intended rather than trying to reinvent the wheel. It essentially reads the string backwards and uses the String object's replaceFirst method, this is exactly what I was looking for.

Here is the documentation on replaceFirst String method and the StringBuffer's reverse function: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceFirst-java.lang.String-java.lang.String-

https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#reverse--

Here is how I implemented it to simply remove some html 'pre' tags from a code snippet that I wanted to interpret. Remember to reverse your search string as well, and then reverse everything back to normal afterwords.

private String stripHtmlPreTagsFromCodeSnippet(String snippet) {
    String halfCleanSnippet = snippet.replaceFirst("<pre>", "");
    String reverseSnippet = new StringBuffer(halfCleanSnippet).reverse().toString();
    String reverseSearch = new StringBuffer("</pre>").reverse().toString();
    String reverseCleanSnippet = reverseSnippet.replaceFirst(reverseSearch, "");
    return new StringBuffer(reverseCleanSnippet).reverse().toString();
}

使用Apaches StringUtils函数removeEnd()

StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"

whats up with the hassle if you can just do this

word = (String) word.subSequence(0, word.length() -1);

this returns new String without the last part of a String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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