简体   繁体   English

String.split()在Android中无法正常运行

[英]String.split() not behaving in android

I have a code in Java that is meant to get the server info from a Minecraft server. 我有一个Java代码,旨在从Minecraft服务器获取服务器信息。 This returns data split by §. 这将返回除以§的数据。 In eclipse, when run as an application, the code works fine. 在eclipse中,当作为应用程序运行时,代码可以正常工作。 The issue is when I bring it to Android. 问题是当我将其带到Android上时。 I have done some research on this but haven't been able to find a working solution. 我对此进行了一些研究,但未能找到可行的解决方案。 (Have tried Pattern.quote("§")) Here is an example of what I'm running: (已尝试过Pattern.quote(“§”))这是我正在运行的示例:

String input = "Look like this§0§25";
String[] data = input.split("§");

The expected data would be a 3-long String[] with the values "Look like this", "0", and "25". 期望的数据将是一个3长度的String [],其值为“看起来像这样”,“ 0”和“ 25”。 This is what happens in eclipse. 这就是日蚀发生的情况。 In android, I get a 1-long String[] with the value "Look like this§0§25". 在android中,我得到一个1-long String [],其值为“ Look likethis§0§25”。 Does anyone know if this is an issue with android or am I doing something wrong? 有谁知道这是android的问题还是我做错了什么?

It is clearly an encoding issue. 显然,这是一个编码问题。 I copied the string directly from your question and pasted in Android Studio. 我直接从您的问题中复制了字符串,然后将其粘贴到Android Studio中。 Then, run this code segment: 然后,运行以下代码段:

String input = "Look like this§0§25";
String[] data = input.split("§");

for (int i = 0; i < data.length; i++)
    Log.v("data[" + i + "] ->", data[i]);

The output was what you ask: 输出是您要求的:

V/data[0] ->﹕ Look like this
V/data[1] ->﹕ 0
V/data[2] ->﹕ 25

Alternatively, you may use StringTokenizer as follows: 或者,您可以按如下方式使用StringTokenizer:

StringTokenizer tokens = new StringTokenizer(input, "§");
String nextToken = tokens.nextToken();

However, if you do not match the character codes properly, both methods will not work. 但是,如果您没有正确匹配字符代码,则这两种方法都将无效。

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

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