-9

嗨,我正在弄清楚如何拆分字符串,所以这是我的代码:因为我使用 bufferedreader 并且我有两个文本框,所以它读取两个文本框(我输入 john 的第一个文本框),我输入 peter 的第二个文本框)输出是johnpeter 所以我试图拆分文本框而不是直接读取 1 行。

BufferedReader reader = new BufferedReader(new InputStreamReader(
            req.getInputStream()));
         String name;

    while ((name = reader.readLine().toString()) != null) 
    {

        Statement stmt;


  String[] players = name.split("");
        String playerO = players[1]; 
        String playerX = players[2];

当前输出为:

Player 1 :j
Player 2 :o

我希望我的输出是:

Player 1 :john
Player 2 :peter
4

3 回答 3

3

照原样,您将无法将字符串拆分到您想要的位置,因为没有明确的分隔符。如果您将其存储为“john peter”或“john,peter”或类似的名称,则拆分会更容易。

那么你只需要改变

String[] players = name.split("");

String[] players = name.split(" ");

或者String[] players = name.split(",");

另外,正如其他人所提到的,请记住第一项playersplayers[0],而不是players[1]

于 2013-07-17T18:06:21.827 回答
1

正如其他人所暗示的那样,您的原始字符串“johnpeter”需要改为

"john,peter,joey,tom,dick,harry";

那么你也能

String name = "john,peter,joey,tom,dick,harry"; 
String[] players = name.split(",");
String playerO = players[0]; 
String playerX = players[1];


System.out.println("Player 1 :" + players[O]);//or, playerO
System.out.println("Player 2 :" + players[1]);//or, playerX

还要注意数组的零基。希望这可以帮助!

于 2013-07-17T18:11:25.190 回答
0

我不确定自从拆分(“关于什么”)以来你想做什么。

如果名称之间有空格,请尝试这样的事情,

    String name = "john peter";
    String[] players = name.split(" ");
    String playerO = players[0];
    String playerX = players[1];


    System.out.println("Player 1 :" +playerO);
    System.out.println("Player 2 :" +playerX);

如果你想拆分(“??”)应该有(拆分什么)标识符

于 2013-07-17T18:08:08.010 回答