How do I get this part of a String

Question from RaiderRoss#6666

hey

ik this might sound stupid but i need help with some string manipulation

int pos = e.getMessage().getContentRaw().lastIndexOf(" ");

So this is my code, my String would look like this

~ban @RaiderRoss This is the whole reason including spaces
                 -----------------------------------------

how would i get the underlined part as a string

so like the second index basically

Once you have an index, you can trim the string from that point forward using substring.

so

String messageRaw = e.getMessage().getContentRaw();
String reason = messageRaw.substring(messageRaw.lastIndexOf(" "));

But in your case it seems like you would only get spaces. Instead, we can split on spaces.

String messageRaw = e.getMessage().getContentRaw();
String[] words = messageRaw.split(' ');

then join, skipping the first two

how do I join

skipping the first two

String messageRaw = "a b c ";
String[] words = messageRaw.split(" ");
String reason = Arrays.stream(words)
        .skip(2)
        .collect(Collectors.joining(" "));

btw our teacher never thought us any of this I got to learn it all on my own so ty for the help

This is one way. You can also do it manually or instead just find the index of the 2nd space and take a substring after that.

https://stackoverflow.com/questions/19035893/finding-second-occurrence-of-a-substring-in-a-string-in-java/35155037

String messageRaw = "a b c ";
String reason = messageRaw.substring(messageRaw.indexOf(" ", messageRaw.indexOf(" ") + 1));

and you can also use regex if you feel brave

ok i got it now ty sm for the help


<- Index