0

How can you split a given string and use its content as Integers in java

I have an input of strings with numbers and I want to perform arithmetic operations on them

15th May 2020, 8:35 AM
utsav mittal
1 Answer
+ 2
Use split() method of String class and Integer.parseInt() method. Example : public class Program { public static void main(String[] args) { String str = "12 45 89 56 23"; String[] numbers = str.split("\\s+"); int sum = 0; for(String number:numbers){ sum += Integer.parseInt(number); } System.out.println("Sum is "+sum); } } split method takes a delimiter to split string. "\\s+" - This is a regular expression to match 1 or more spaces. \\s - match space + - match 1 or more occurances of preceding element. Integer.parseInt() converts string to integer. If it's not convertible it'll throw NumberFormatException
15th May 2020, 9:00 AM
šŸ‡®šŸ‡³OmkaršŸ•‰
šŸ‡®šŸ‡³OmkaršŸ•‰ - avatar