Anonymouse Anonymouse
Anonymouse Anonymouse

Reputation: 11

Save as an int from charAt

E.g:

public static void test() {
    int x = 0 ;
    String line = "A24 ASD 46" ;
    for ( int i = 0 ; i < line.length() ; i++) {
        if (Character.isDigit(line.charAt(i))) {
            int number = line.charAt(i) ;
            System.out.println(number);
        }
    }
}

"x" is printing the ASCII value of a char, and not the element of String at index "i" ! How to print the element in index of a String ?

Upvotes: 0

Views: 193

Answers (2)

Karol Dowbecki
Karol Dowbecki

Reputation: 44980

If you want to find digits using streams:

String line = "A24 ASD 46";
line.chars()
    .filter(Character::isDigit)
    .mapToObj(Character::toString)
    .forEach(System.out::print);

will print 2446.

Upvotes: 0

Ruslan
Ruslan

Reputation: 6300

If you really need int value here, there is getNumericValue() for this case:

int number = Character.getNumericValue(line.charAt(i))

But if you want just print all numbers from the source string, you don't have to convert char to int as @Deadpool mentioned. Just do System.out.println(line.charAt(i));

Upvotes: 2

Related Questions