Reputation: 123
I am trying to find a way to have access to a specific string after a bigger string is broken down into smaller strings. Below is an example: So now that there are two strings, how do I get the first or second? Since there are brackets, I thought that it is an array of string so I thought all I had to do was do something like System.out.println(parts[0]); But that doesnt work..
String string = "hello ::= good morning";
String parts = Arrays.toString(string.split("::="));
System.out.println(parts);
the output should be [hello, good morning]
Upvotes: 0
Views: 64
Reputation: 201507
This looks like a better use case for pattern grouping with a regular expression to me. I would group the left-hand side and right-hand side of ::=
preceded and followed by optional white-space. For example,
String string = "hello ::= good morning";
Pattern p = Pattern.compile("(.+)\\s*::=\\s*(.+)");
Matcher m = p.matcher(string);
if (m.find()) {
System.out.println(m.group(2));
}
Which outputs
good morning
If you also wanted "hello" that would be m.group(1)
Upvotes: 0
Reputation: 7917
It works fine if you just remove Arrays.toString(...
:
String string = "hello ::= good morning";
String parts[] = string.split("::=");
System.out.println(parts[0]);
Update:
To print the whole array, you can do this:-
System.out.println(Arrays.toString(parts));
Also, to trim the spaces, you can change the split line to:-
String parts[] = string.trim().split("\\s*::=\\s*");
Upvotes: 2
Reputation: 108
You need to put it an array like so:
String s = "I Like Apples."
String[] parts = s.split(" ");
for(String a : parts)
System.out.println(a);
Upvotes: 3