1

In my application I am trying to make breadcrumbs using StringBuilder

Suppose this is the string :

String1>String2>String3>String4>String5>

Now I want to remove String5> and I want string like this:

String1>String2>String3>String4>

How can I do this?

Please help!!

Android
  • 133
  • 3
  • 13
  • 1
    possible duplicate of http://stackoverflow.com/questions/10828313/remove-string-after-last-occurrence-of-character-android-java – mandar Feb 11 '17 at 06:16
  • my question is different. please read carefully.. @mandar – Android Feb 11 '17 at 06:48
  • `public StringBuilder delete(int start,int end)` Removes the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made. Parameters: `start - The beginning index, inclusive. end - The ending index, exclusive.` – Mehran Zamani Feb 11 '17 at 12:35

3 Answers3

4

you can use regex \\w+>$

\\w+ mean match [a-zA-Z0-9_]

>$ match > character where $ mean at the end

Regex Demo Link

    String s  = "String1>String2>String3>String4>String5>";
    String s2 = s.replaceAll("\\w+>$","");
    System.out.println(s2);

Output :

String1>String2>String3>String4>

Note : To avoid _ use

    String s2 = s.replaceAll("[a-zA-Z\\d]+>$","");

Just in case if you have data with some special characters like

String s = "String1>Stri$#$ng2>String3>Stri#$$#ng4>St$#:/|ring5>";

then above solution won't work so you can use

    String s2 = s.replaceAll("[^>]+>$","");
    // s2 will be = String1>Stri$#$ng2>String3>Stri#$$#ng4>

Regex Demo Link

[^>]+ : ^ inside [] works as negation mean match everything except > character

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
0

Split string by > and then apply for loop on the array. match string by position. if match then delete otherwise add to new stringBuilder.

Rajkumar Kumawat
  • 290
  • 2
  • 11
0

You can use combination of lastIndexOf and substring().

Example:

String oldValue = "String1>String2>String3>String4>String5>";
int lastIndex = oldValue.lastIndexOf('>', oldValue.length() - 2);
String newValue = oldValue.substring(0, lastIndex + 1);
algojava
  • 743
  • 4
  • 9