简体   繁体   中英

when I split a string into multiple strings, how do I get a certain part of that string?

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]

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM