0

I have String which I want to convert into Integer.

example - I have string in below format

Input : ABCD00000123

Output: 123

Thanks in Advance

3 Answers 3

8
// First remove all non number characters from String 
input= input.replaceAll( "[^\\d]", "" );  
// Convert it to int
int num = Integer.parseInt(input);

For example

input = "ABCD00000123"; 

After

input= input.replaceAll( "[^\\d]", "" );   

input will be "00000123"

 int num = Integer.parseInt(input);

int will be 123.

This is one of the simple solution if the input is always in the format mentioned in the question. There can be multiple scenarios considering position of numeric characters with respect to non numberic characters like
0123ABC
0123ABC456
ABC0123DE

Sign up to request clarification or add additional context in comments.

4 Comments

This is a good answer, but as a note: input = "A3B32BDC2"; will yield 3322 as its output, which might not be desired.
@SteveP.: Thanks. Was about to add it. Updated my answer.
Just a doubt, isn't \D the pattern for non-digit characters?, why using [^\\d]?
@Daniel: \d matches any single digit (equivalent to the class [0-9]). Conversely, capital \D means any non-digit. I think \d will be appropriate choice here.
1
String s = "ABCD00000123"
int output = Integer.parseInt(s.subString(4));

System.out.println(output);

2 Comments

What about String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-=_+|\{}<00000123"?
@LuiggiMendoza I would argue that it isn't in the format he specified, but as the question wasn't very clear, it's difficult to know exactly what he is looking for.
0

I can tell yo the logic for it... convert this String into a character array, and then parse it from the first index (0 for array), up to length and check the first non-zero integer number, then from that location to the remaining length of the String copy this to another String and then parse it using Integer.parseInt();

String val = "ABCD00000123";
String arr[] = val.toCharArray();
int cnt;
for(cnt = 0 ; cnt < arr.length; cnt++){
switch(arr[cnt]){

/*Place your logic here to check the first non-zero number*/

}
}

and then follow the remaining logic.

if you have enough programming concepts then only you can do it...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.