简体   繁体   English

Split() - 在java中

[英]Split()-ing in java

So let's say I have: 所以我要说:

String string1 = "123,234,345,456,567*nonImportantData";
String[] stringArray = string1.split(", ");

String[] lastPart = stringArray[stringArray.length-1].split("*");
stringArray[stringArray.length-1] = lastPart[0];

Is there any easier way of making this code work? 有没有更简单的方法来使这个代码工作? My objective is to get all the numbers separated, whether stringArray includes nonImportantData or not. 我的目标是将所有数字分开,无论stringArray是否包含nonImportantData。 Should I maybe use the substring method? 我应该使用子串方法吗?

Actually, the String.split(...) method's argument is not a separator string but a regular expression. 实际上,String.split(...)方法的参数不是分隔符字符串而是正则表达式。

You can use 您可以使用

String[] splitStr = string1.split(",|\\*");

where | 哪里| is a regexp OR and \\\\ is used to escape * as it is a special operator in regexp. 是一个正则表达式OR和\\\\用于转义*因为它是regexp中的特殊运算符。 Your split("*") would actually throw a java.util.regex.PatternSyntaxException. 你的split(“*”)实际上会抛出java.util.regex.PatternSyntaxException。

I'd probably remove the unimportant data before splitting the string. 我可能会在拆分字符串之前删除不重要的数据。

int idx = string1.indexOf('*');
if (idx >= 0)
  string1 = string1.substring(0, idx);
String[] arr = string1.split(", ");

If '*' is always present, you can shorten it like this: 如果'*'始终存在,您可以像这样缩短它:

String[] arr = str.substring(0, str.indexOf('*')).split(", ");

This is different than MarianP's approach because the "unimportant data" isn't preserved as an element of the array. 这与MarianP的方法不同,因为“不重要的数据”不会作为数组的元素保留。 This may or may not be helpful, depending on your application. 根据您的应用,这可能有用也可能没用。

Assuming you always have the format you've provided.... 假设你总是拥有你提供的格式....

String input = "123,234,345,456,567*nonImportantData";
String[] numbers = input.split("\\*")[0].split(",");

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

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