我想在冒号字符上拆分java中的一些字符串。
字符串的格式为:Account:Password
.
我想分隔标记:Account
和Password
. 最好的方法是什么?
先看欧内斯特弗里德曼希尔的回答。
String namepass[] = strLine.split(":");
String name = namepass[0];
String pass = namepass[1];
// do whatever you want with 'name' and 'pass'
不确定您需要帮助的部分,但请注意,split()
上面的调用永远不会返回单元素数组以外的任何内容,因为根据定义,当它看到一个字符readLine()
时会停止。,另一方面,对你来说应该很方便......\n
split(":")
您需要使用拆分(“:”)。试试这个-
import java.util.ArrayList;
import java.util.List;
class Account {
String username;
String password;
public Account(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
class Solution {
public static void main(String[] args) {
while(.....){//read till the end of the file
String input = //each line
List<Account> accountsList = new ArrayList<Account>();
String splitValues[] = input.split(":");
Account account = new Account(splitValues[0], splitValues[1]);
accountsList.add(account);
}
//perform your operations with accountList
}
}
希望能帮助到你!