嗨,我正在弄清楚如何分割字符串,以便我的代码: 因为我使用bufferedreader,我有两个文本框,所以它读取文本框(第一个文本框我键入约翰),第二个文本框我输入彼得)输出是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
答案 0 :(得分:3)
按原样,您将无法将字符串拆分到您想要的位置,因为没有明确的分隔符。如果你把它存储为“john peter”或“john,peter”或类似的东西,它会更容易分裂。
然后你只需要改变
String[] players = name.split("");
要
String[] players = name.split(" ");
或String[] players = name.split(",");
另外,正如其他人提到的那样,请记住players
中的第一项是players[0]
,而不是players[1]
答案 1 :(得分: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
注意数组的零基数。希望这有帮助!
答案 2 :(得分: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);
如果你想拆分(“??”),应该有(拆分什么)标识符