Home > Enterprise >  how to reverse only numbers in a string
how to reverse only numbers in a string

Time:09-25

INPUT : 123ABC458 OUTPUT : 321ABC854

 public static void main(String []args){
    String str="123ABC564";
   int count=0;
   int ans=0;
   int firstindex=0;
   char[] ch = str.toCharArray();
   for(int i=0;i<ch.length;i  ){
       if(Character.isDigit(ch[i])){
       if(ans==0){
            firstindex=i;
            
       }
       count  ;
       
   }
   else{
       int lastindex=count firstindex-1;
       while(firstindex<lastindex){
    char temp=ch[firstindex];
    ch[firstindex]=ch[lastindex];
    ch[lastindex]=temp;
    firstindex  ;
    lastindex--;
}
 ans=0;
  count=0;
  firstindex=0;
   }
   }
    for (char c : ch){
        System.out.print(c);
    }
}

}

Can anyone tell me what's wrong with this code The output which I am getting using this code is 12BA3C564

CodePudding user response:

Here is a concise version using string splitting:

String input = "123ABC458";
String[] parts = input.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
    if (part.matches("\\d ")) {
        StringBuilder num = new StringBuilder(part);
        sb.append(num.reverse());
    }
    else {
        sb.append(part);
    }
}

System.out.println(sb.toString());  // 321ABC854

The splitting operation used above generates a string array of either numbers or letters. Then, we iterate that array and selectively reverse the number strings using StringBuilder#reverse.

CodePudding user response:

You can use the Java regex API and StringBuilder to solve it easily. The regex, \d specifies one or more digits. Using the Java regex API, you find the numbers, their start position and the end positions which you can use to build the required string.

Demo:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Tests
        String[] samples = { "123ABC458", "123ABC458XYZ", "123ABC458XYZ367", "ABC123XYZ", "ABC123XYZ" };
        for (String s : samples)
            System.out.println(numbersInverted(s));

    }

    static String numbersInverted(String str) {
        StringBuilder sb = new StringBuilder();
        Matcher matcher = Pattern.compile("\\d ").matcher(str);
        int lastInitailPos = 0;
        while (matcher.find()) {
            int start = matcher.start();
            String inverted = new StringBuilder(matcher.group()).reverse().toString();
            sb.append(str.substring(lastInitailPos, start)).append(inverted);
            lastInitailPos = matcher.end();
        }
        if (sb.length() == 0) // If no number was found
            return str;
        else
            return sb.append(str.substring(lastInitailPos)).toString();
    }
}

Output:

321ABC854
321ABC854XYZ
321ABC854XYZ763
ABC321XYZ
ABC321XYZ

ONLINE DEMO

CodePudding user response:

You can get all the numbers from the string as first move, and then replace the input with the reversed string of the numbers. Example:

public static void main(String[] args)
{
    String input = "123ABC458";
    Matcher m = Pattern.compile("\\d ").matcher(input);
    while(m.find()) 
        input = input.replace(m.group(), new StringBuilder(m.group()).reverse());
    
    System.out.println(input);
}
  • Related