-5

I have a string like this:

"hello I am a example example"

I have get the last word of the string like this

 String lasttWord = mystring.substring(mystring.lastIndexOf(" ")+1);

but I can´t split this because the word is repeated

How can I remove the last word only?

user3733523
  • 151
  • 1
  • 2
  • 11
  • Please share your research and your attempts including a description of how you debugged it and what your own hypothesis of the problem is. – Jeroen Vannevel Feb 27 '16 at 15:17
  • Sounds like a lot of work? Alternatively: consider searching for your problem first. http://stackoverflow.com/questions/8694984/remove-part-of-string – Jeroen Vannevel Feb 27 '16 at 15:18
  • In this example there is not a repeated word ;) @JeroenVannevel – user3733523 Feb 27 '16 at 15:20
  • What exactly do you want to do? Do you want to remove the last word if the same word is before it? Or do you want to do it for the whole String? What would the result be for `"example lala example"` and `"example example lala"`? – Tunaki Feb 27 '16 at 15:23

2 Answers2

1

Split the string by space and rename the last word. Then using the StringBuilder concatenate them together back to your original String.

String str = "hello I am a example example"
String[] parts = str.split(" ");
parts[parts.length-1] = "moon";
System.out.println(parts[parts.length-1]); 
StringBuilder sb = new StringBuilder();
for (int i=0; i<parts.length; i++) {
   sb.append(parts[i]);
   sb.append(" ");
}
str = sb.toString();
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

If you are looking to remove the duplicates from your String and not sure of the positions of the duplicates occurrences then you can try using both a list (to maintain order) and a set (to remove duplicates).

You can then rebuilt your String using the list without duplicates.

Here is the code snippet:

public static void main (String[] args)
{
    String str = "hello I am a example example"; 
    String[] tokens = str.split(" ");
    Set<String> set = new HashSet<>();
    List<String> list = new ArrayList<>();
    for(String token : tokens) {
        if(!set.contains(token)) {
            set.add(token);
            list.add(token);
        }
    }

    /* Print String */
    for(int i = 0; i < list.size(); i++)
        System.out.print(list.get(i) + " ");
}

Output:

hello I am a example
user2004685
  • 9,548
  • 5
  • 37
  • 54