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?
split() method to split a string on the colons, e.g. my_list = my_str. split(':') . The str. split method will split the string on each occurrence of a colon and will return a list containing the results.
split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.
String class provides split() method to split String in Java, based upon any delimiter, e.g. comma, colon, space or any arbitrary method. split() method splits the string based on delimiter provided, and return a String array, which contains individual Strings.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With