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.
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.
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)); } } 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."
Source: https://ru.stackoverflow.com/questions/634097/
All Articles