How to split a string in Java

appropriate method: String#split().


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

To test beforehand if the string contains a -, just use String#contains().
if (string.contains("-")) 
 {  
// Split it. 
 } else  
{ 

 throw new IllegalArgumentException("String " + string + " does not contain -");  

}

Comments