1

If a client wants to store a message into a txt file, user uses keyword msgstore followed by a quote.

Example: msgstore "ABC is as easy as 123"

I'm trying to split msgstore and the quote as two separate elements in an array.

What I currently have is:

String [] splitAdd = userInput.split(" ", 7);

but the problem I face is that it splits again after the second space so that it's:

splitAdd[0] = msgstore
splitAdd[1] = "ABC
splitAdd[2] = is

My question is, how do I combine the second half into a single array with an unknown length of elements so that it's:

splitAdd[0] = msgstore
splitAdd[1] = "ABC is as easy as 123"

I'm new to java, but I know it's easy to do in python with something like (7::).

Any advice?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • The Properties class is designed for this use-case however it wants you to format your 'messages' as follows: msgname=the message you want to associate with this property name. If you are open to formatting your messages in this way, simply place them in a text file, and then use the load method. Here's a link to some useful documentation https://www.baeldung.com/java-properties – Tom Drake Oct 18 '18 at 05:10
  • Your Python example doesn't seem to do a split string on space, it seems to apply a substring. Maybe you're just looking for `userInput.substring(9)` instead? (the equivalent of python`userInput[9:]`)? – Mark Rotteveel Oct 18 '18 at 15:52

3 Answers3

1

substring on the first indexOf "

String str = "msgstore \"ABC is as easy as 123\"";

int ind = str.indexOf(" \"");

System.out.println(str.substring(0, ind));
System.out.println(str.substring(ind));

edit

If these values need to be in an array, then

String[] arr = { str.substring(0, ind), str.substring(ind)};
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

Why do you have limit parameter as 7 when you want just 2 elements? Try changing it to 2:-

String splitAdd[] = s.split(" ", 2);

OR

String splitAdd[] = new String[]{"msgstore", s.split("^msgstore ")[1]};
Kartik
  • 7,677
  • 4
  • 28
  • 50
0

You can use RegExp: Demo

Pattern pattern = Pattern.compile("(?<quote>[^\"]*)\"(?<message>[^\"]+)\"");
Matcher matcher = pattern.matcher("msgstore \"ABC is as easy as 123\"");

if(matcher.matches()) {
    String quote = matcher.group("quote").trim();
    String message = matcher.group("message").trim();
    String[] arr = {quote, message};

    System.out.println(Arrays.toString(arr));
}

This is more readable than substring a string, but it definetely slower. As alternative, you can use substirng a string:

String str = "msgstore \"ABC is as easy as 123\"";
int pos = str.indexOf('\"');
String quote = str.substring(0, pos).trim();
String message = str.substring(pos + 1, str.lastIndexOf('\"')).trim();
String[] arr = { quote, message };
System.out.println(Arrays.toString(arr));
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35