简体   繁体   English

如何将字符串转换为字符串数组?

[英]How to turn a string into an array of strings?

For example, I want a string "1:00 pm 2:00 pm 3:00 pm" to turn into an array of a string of ["1:00 pm", "2:00 pm", "3:00 pm"] 例如,我希望将字符串"1:00 pm 2:00 pm 3:00 pm"转换为字符串数组["1:00 pm", "2:00 pm", "3:00 pm"]

I've tried using split. 我试过使用拆分。 But it would produce ["1:00", "pm", "2:00", "pm", "3:00", "pm"] . 但是它将产生["1:00", "pm", "2:00", "pm", "3:00", "pm"] How would I split every other space? 我将如何分割其他空间? Thank you. 谢谢。

split using regular expression, Regular expression (?<=m) to split the string using m as delimiter and including it. 使用正则表达式进行split ,正则表达式(?<=m)使用m作为分隔符拆分字符串并将其包括在内。 But there will be extra empty character from second element you can use trim() method to remove it 但是第二个元素中会有多余的空字符,您可以使用trim()方法将其删除

String s =  "1:00 pm 2:00 pm 3:00 pm";

String[] arr = s.split("(?<=m)");

System.out.println(Arrays.toString(arr));   //[1:00 pm,  2:00 pm,  3:00 pm]

For your problem I might suggest using a formal Java regex matcher. 对于您的问题,我建议您使用正式的Java正则表达式匹配器。 The reason for this is that perhaps your time strings could appear as part of a larger string. 原因是您的时间字符串可能会显示为较大字符串的一部分。

String input = "1:00 pm 2:00 pm 3:00 pm";
String pattern = "(?i)\\d{1,2}:\\d{2} [ap]m";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
     System.out.println("Found a time: " + m.group(0));
}

This prints: 打印:

Found a time: 1:00 pm
Found a time: 2:00 pm
Found a time: 3:00 pm

You could use Java's indexOf method to find the index of each space and only take into account every other one. 您可以使用Java的indexOf方法查找每个空间的索引,而仅考虑其他每个索引。 Then, create a sub string using your knowledge of the spaces and add it to your array. 然后,使用您对空格的了解创建一个子字符串,并将其添加到您的数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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