How to split a string in Java?

Answer

Just use the appropriate method: String#split().

String string ="004-034556";String[] parts = string.split("-");String part1 = parts[0];// 004String part2 = parts[1];// 034556

Note that this takes a regular expression, so remember to escape special characters if necessary, e.g. if you want to split on period . which means "any character" in regex, use either split("\\.") or split(Pattern.quote(".")).

To test beforehand if the string contains a -, just use String#contains().

if(string.contains("-")){// Split it.}else{thrownewIllegalArgumentException("String "+ string +" does not contain -");}

All windows Questions

Ask your interview questions on windows

Write Your comment or Questions if you want the answers on windows from windows Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---