Extract string and int from string

I have a line: RoomA38 . I want to extract RoomA from it and put an object of type String, extract 3 and 8 and put them into two different types of int.I was thinking about splitting the method, but I don't know how to use this in this case. How can i do this?

+4
source share
9 answers

Could you do something like this?

 String myString = "RoomA38"; StringBuilder sb = new StringBuilder(); List<Integer> numbers = new ArrayList<Integer>(); for(int i=0;i<myString.length();i++){ char c = myString.charAt(i); if(!Character.isDigit(c)){ sb.append(c); }else{ numbers.add(Integer.parseInt(c+"")); } } String roomString = sb.toString(); for(Integer i : numbers){ //use the number i } 
+3
source

You can do this in different ways, you just need some kind of calculation, there are no specific api or build methods. You can also do this below.

  String str = "RoomA38"; int number = 0; String[] strArr = str.split("\\d"); str = str.replace(strArr[0], ""); number = Integer.parseInt(str); System.out.println("Numbers::: " + number); str = strArr[0]; System.out.println("String is:::: " + str); 
+2
source
 public static void main(String[] args) { String str = "RoomA3814221"; String pattern = "[0-9]+"; Scanner sc = new Scanner(str); String result = sc.findInLine(pattern); String[] arr = result.split(""); System.out.println(result); System.out.println(arr.length); for (String s: arr) { System.out.println(s); } } 
+1
source
0
source

using the following line, you can find out if char digit. Character.isDigit ('');

you can iterate over each char string in a string and extract useful characters accordingly.

0
source

You can extract Numbers from a string after that, write your own logic and to separate the numbers.

Thanks Sunil

0
source

if the format is always the same:

  String value = "RoomA38"; String room = value.substring(0, 5); Integer floor = Integer.valueOf(value.substring(5,6)); Integer roomNumber = Integer.valueOf(value.substring(6,7)); 
0
source

Why not use RegEx?

 @Test public void splitString() { final String src = "RoomA38"; final Pattern pattern = Pattern.compile("(\\D*)(\\d*)"); final Matcher matcher = pattern.matcher(src); matcher.matches(); final String resultString = matcher.group(1); final int resultInt = Integer.valueOf(matcher.group(2)); Assert.assertEquals("RoomA", resultString); Assert.assertEquals(38, resultInt); } 
0
source

Extract desired result using regex and pattern matching in java

 String chars; int result2,result3; String str= "RoomA38"; String regex ="([a-zA-Z]+)([0-9]{1})([0-9]{1})"; Matcher matcher = Pattern.compile( regex ).matcher( str); while (matcher.find( )) { result = matcher.group(1); result2 =Integer.parseInt(matcher.group(2)); result3 = Integer.parseInt(matcher.group(3)); System.out.println("chars="+result+" "+"number1="+result2+" "+"number2="+result3); } chars=RoomA number1=3 number2=8 
0
source

Source: https://habr.com/ru/post/1385324/


All Articles