9

我想在冒号字符上拆分java中的一些字符串。

字符串的格式为:Account:Password.

我想分隔标记:AccountPassword. 最好的方法是什么?

4

3 回答 3

28

先看欧内斯特弗里德曼希尔的回答。

String namepass[] = strLine.split(":"); 
String name = namepass[0]; 
String pass = namepass[1];
// do whatever you want with 'name' and 'pass'
于 2012-04-04T02:17:16.560 回答
7

不确定您需要帮助的部分,但请注意,split()上面的调用永远不会返回单元素数组以外的任何内容,因为根据定义,当它看到一个字符readLine()时会停止。,另一方面,对你来说应该很方便......\nsplit(":")

于 2012-04-04T02:08:10.377 回答
2

您需要使用拆分(“:”)。试试这个-

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
    }
}

希望能帮助到你!

于 2012-04-04T02:12:53.767 回答