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?

2
  • 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 baeldung.com/java-properties Commented Oct 18, 2018 at 5: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 pythonuserInput[9:])? Commented Oct 18, 2018 at 15:52

3 Answers 3

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]};
Sign up to request clarification or add additional context in comments.

Comments

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)};

Comments

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.