-2
Input > 
user_input = 123456789
format = "xx-xxx-x-xx-x"

Output >
12-345-6-78-9

Or

Input > 
user_input = 123456
format = "x-xx-x-x-x"

Output >
1-23-4-5-6

I do everything i can and try to another language(python,js) but it not work.

it have problem after else statement

String a = "123456";
String b = "xxx-xx-x";

char[] c_arr = b.toCharArray();

for (int i = 0; i < b.length(); i++) {
    if(c_arr[i] != '-'){
        c_arr[i] = a.charAt(i);
    } else {
        c_arr[i+1] = a.charAt(i);
    }
    System.out.println(c_arr);
}
ifly6
  • 5,003
  • 2
  • 24
  • 47
salmorn
  • 13
  • 2
  • Possible duplicate of [How do I format a number in Java?](https://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java) – Ele Jan 30 '18 at 16:58
  • @Ele it difference that post cause my code have a format from user input – salmorn Jan 30 '18 at 17:01
  • It's because your `b` string is longer than your `a` string. – ifly6 Jan 30 '18 at 17:04

1 Answers1

1

This code here will solve your problem. What is happening is that your counter variable exceeds the length of the a string. To solve that, use a separate counter which iterates through that string that increments as the characters are consumed.

String a = "123456";
String b = "xxx-xx-x";

char[] cArray = b.toCharArray();
int aPos = 0; // create separate counter

for (int i = 0; i < b.length(); i++) {
    if (cArray[i] == '-') continue; // if skipping, do not increment aPos, continue
    cArray[i] = a.charAt(aPos);
    aPos++; // add counter when we used the charAt

    System.out.println(cArray);
}

This could still break, however, because there could be more positions that are declared in b that need to be filled than there are consumable characters in a. I would recommend doing a runtime check to throw an exception if there is an input mismatch.

ifly6
  • 5,003
  • 2
  • 24
  • 47
  • `if (cArray[i] == '-') continue; rest of code` is similar to `if (cArray[i] == '-'){continue;} else {rest of code}`. In this situation we can rewrite current code as `if(cArray[i]=='x'){cArray[i] = a.charAt(aPos++);}` - System.out.... should also be placed outside of loop. – Pshemo Jan 30 '18 at 17:48
  • Yea, if we weren’t showing the working. The OP has the print statement inside because he wants to know what is going on. I left it in so he could see what is going on. – ifly6 Jan 30 '18 at 17:53