Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Splitting an input file by colons

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?

like image 466
user1304317 Avatar asked Apr 04 '12 02:04

user1304317


People also ask

How do you split a string into a colon?

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.

What does split \\ s+ do in Java?

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.

How do you take input from the user as a single string separating each field with a colon (:) in Java?

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.


2 Answers

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'
like image 89
mshsayem Avatar answered Nov 02 '22 05:11

mshsayem


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

like image 33
Ernest Friedman-Hill Avatar answered Nov 02 '22 03:11

Ernest Friedman-Hill