Java Android 将字符串转换为数组字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18783300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:01:36  来源:igfitidea点击:

Android converting string to array string

javaandroidregexarraysstring

提问by Tenaciousd93

I have a string like this:

我有一个这样的字符串:

["477","com.dummybilling","android.test.purchased","inapp:com.dummybilling:android.test.purchased","779"]

How to have a String[] with these 5 element? Does anyone know a regex for .split()method?

如何使用这 5 个元素创建 String[]?有人知道.split()方法的正则表达式吗?

Thank you very much, regular expressions make me crazy! :(

非常感谢,正则表达式让我抓狂!:(

采纳答案by Ravi Thapliyal

Process it as JSON. Two immediate benifits would be that it would take care of any embedded commas in your data automatically and the other that you would get a String[]with unquotedstrings.

将其处理为 JSON。两个直接的好处是它会自动处理数据中的任何嵌入逗号,另一个好处是你会得到一个不String[]引号的字符串。

String input = "[\"477\",\"com.dummybilling\",\"android.test.purchased\",\"inapp:com.dummybilling:android.test.purchased\",\"779\"]";

JSONArray jsonArray = new JSONArray(input);
String[] strArr = new String[jsonArray.length()];

for (int i = 0; i < jsonArray.length(); i++) {
    strArr[i] = jsonArray.getString(i);
}

System.out.println(Arrays.toString(strArr));

Output:

输出

[477, com.dummybilling, android.test.purchased, inapp:com.dummybilling:android.test.purchased, 779]

回答by zzheng

You can split your string by separator ["(the beginning) or ","or "](the ending) like this:

您可以按分隔符["(开头)或",""](结尾)分割字符串,如下所示:

final String[] tokens = yourString.split("\",\"|\[\"|\"\]");

Please note that this will only work for your string. It's not a general solution (for example, it does not take care of any escaped quotes). If your string is in JSON format, you should use a JSON parser as proposed by @Ravi Thapliyal .

请注意,这仅适用于您的字符串。这不是通用解决方案(例如,它不处理任何转义引号)。如果您的字符串是 JSON 格式,您应该使用 @Ravi Thapliyal 建议的 JSON 解析器。