How to compare a string's 1st character with a integer in java | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

How to compare a string's 1st character with a integer in java

Example String s="1234" int i =1 I want to compare s[0] with i

6th Feb 2021, 7:16 AM
Rishab Solanki
Rishab Solanki - avatar
5 ответов
+ 5
boolean result = ( Integer.valueOf( s.charAt( 0 ) ) - '0' == i ); This assumes string <s> contains only digits.
6th Feb 2021, 7:24 AM
Ipang
+ 6
Rishab Solanki As you know that String is a character of sequence and also String is a class which has method charAt(index) so you can get 1st character using charAt(0) Since it will return character not integer so you need to get is as a integer using Integer.valueOf() method. If you want to get 1st character using s[0] then you need to convert String in character array
6th Feb 2021, 8:27 AM
A͢J
A͢J - avatar
+ 1
Can you describe the goal of the code you are attempting to write?
6th Feb 2021, 7:18 AM
Ipang
+ 1
Thank you😊
6th Feb 2021, 7:34 AM
Rishab Solanki
Rishab Solanki - avatar
0
I have explained in example
6th Feb 2021, 7:21 AM
Rishab Solanki
Rishab Solanki - avatar