我有一个类似控制台的小程序,允许通过 JTextField 输入命令。
我写了很多命令,输入被转换为字符串 > 如果一个命令有 ping 一个 IP 属性 (ping 192.168.1.1) 我子字符串 5 (ping),但是现在当我想要几个属性时(命令 atr1 art22 atr333 art4444)我会得到
String command = "command"; //I can make this one
String attribute1 = "atr1"; //I can make this one
String attribute2 = "atr22";
String attribute3 = "atr333";
等等,但是无论长度如何,它都会给我这个属性...因为我可以用子字符串完成所有事情,但它会定义长度!
最佳答案
您可以使用 String.split
:
String cmd = "command atr1 art22 atr333 art4444";
String[] parts = cmd.split(" ");
split 方法允许使用正则表达式。例如,如果空格的数量不同,这很有用:
String cmd = "command atr1 art22 atr333 art4444";
String[] parts = cmd.split(" +"); // split by spans of one or more spaces
关于java - 如何从Java中的字符串中提取部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17213450/