From the server comes a number as a string:

"66" 

How can I get a number from a string without using substring() ?

My mentor gave such a task - I can not think of anything.

  • Do quotes appear in the string? And what about the number of digits in the string, as well as the presence of extraneous characters? - Regent
  • @Regent are included. The number of digits is any, there are no extraneous symbols - Flippy
  • If you get an answer, mark it as accepted. - Mikhail Vaysman

2 answers 2

Use a regular expression

 final String regex = "\"(\\d+)\""; final String string = "\"66\""; final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(string); while (matcher.find()) { System.out.println("Full match: " + matcher.group(0)); for (int i = 1; i <= matcher.groupCount(); i++) { System.out.println("Group " + i + ": " + matcher.group(i)); } } 
  • Thank you so much - Flippy
  • I don’t know if it makes sense to take quotation marks in regular expressions - you just have to get the number. - Regent
  • one
    in my opinion, the stricter the expression, the less false matches. in the original question quotes are. - Mikhail Vaysman

It is possible to detect the first group of numbers in a string and bring them to a number using character-by-line string analysis

 String str = "\"66\""; int number = 0; boolean gotFirstDigit = false; for (char c : str.toCharArray()) { if (c >= '0' && c <= '9') { number = number * 10 + c - '0'; gotFirstDigit = true; } else if (gotFirstDigit) { break; } } System.out.println(number); 

But this is already an option "as an alternative."