I want to split some Strings in java on the colon character.
The format of the strings are: Account:Password.
I want to separate the tokens: Account and Password. What's the best way to do this?
See Ernest Friedman-Hill's answer first.
String namepass[] = strLine.split(":");
String name = namepass[0];
String pass = namepass[1];
// do whatever you want with 'name' and 'pass'
Not sure what part you need help with, but note that the split() call in the above will never return anything other than a single-element array, since readLine(), by definition, stops when it sees a \n character. split(":"), on the other hand, ought to be very handy for you...
split(":") would give you the username and password as two separate array elements, at which point you're free to do whatever you want with them -- that being the goal of the whole enterprise as I understood it.You need to use split(":"). Try this-
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
}
}
Hope it helps!
strLine.split(":")should give you username and passnamepass = strLine.split(":"); name = namepass[0]; pass = namepass[1], shouldn't this do?