-1

Input : "107501AB021F" Output: "1075 1AB 21F"

  1. Assume the input is always of 12 digit hexadecimal value.
  2. For each 2 digit char, if 0 occurs on the first position, it should be replaced with space

I know we can do this with an if condition and a charAt, but is there an option to do this without using it?

Raman
  • 665
  • 1
  • 15
  • 38
  • This is not a code writing service. What did you try so far? Post your code! What happened when you ran it? What did you expect to happen instead? What specifically are you having problems with? https://stackoverflow.com/help/mcve – Robert Nov 23 '17 at 20:54
  • Why don't you just [split it into parts](https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character) and then [do your magic](https://stackoverflow.com/questions/8540015/determine-if-string-starts-with-letters-a-through-i)? – ctwheels Nov 23 '17 at 20:55
  • Robert, please refer to the code in Mr. Bedla's post and that is exactly how I have the code. However, I was wondering if we can do this without using the conditional if statement, that is with the RegEx? – Raman Nov 24 '17 at 01:05
  • With a regex, you can remove them easily, `.replaceAll("\\G(?:0|(.))(.)", "")`. Although you do not even check if the second char is a digit. It cannot be done with a pure regex. – Wiktor Stribiżew Nov 24 '17 at 20:17
  • Thanks Wiktor. That's what I thought too – Raman Nov 25 '17 at 08:04

1 Answers1

0

I believe the most efficient solution is to iterate and compare every second char in char array.

public class ReplaceOddIndexesInString {
    public String replace(final String hex){
        final char[] arr = hex.toCharArray();
        for (int i = 0; i<arr.length; i=i+2) {
            if (arr[i]=='0'){
                arr[i]=' ';
            }
        }
        return new String(arr);
    }

    @Test
    public void testIt(){
        TestCase.assertEquals("1075 1AB 21F", replace("107501AB021F"));
    }
}
Bedla
  • 4,789
  • 2
  • 13
  • 27
  • Thanks Bedla, I have the the exact code, I just wanted to check if there is any other way to achieve this, without using conditional check (6 times) for a given input string. – Raman Nov 24 '17 at 00:59