0

In Android if I have an edit text and the user entered 123456789012, how could I get the program to insert a dash every 4th character. ie: 1234-5678-9012?

I guess you need to say something along the lines of:- a=Characters 1~4, b=Characters 5~8, c=Characters 9-12, Result = a + "-" + b + "-" + c. But I am unsure of how that would look in Android.

Many thanks for any help.

Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
Entropy1024
  • 7,847
  • 9
  • 30
  • 32

3 Answers3

8
String s = "123456789012";
String s1 = s.substring(0, 4);
String s2 = s.substring(4, 8);
String s3 = s.substring(8, 12);

String dashedString = s1 + "-" + s2 + "-" + s3;
//String.format is extremely slow. Just concatenate them, as above.

substring() Reference

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • Brilliant. Thank you for that very clear answer. Much appreciated. – Entropy1024 Nov 12 '10 at 23:23
  • Eclipse underlines substring & I get the following error when I try this The method substring(EditText, int, int) is undefined for the type new View.OnClickListener(){} What should I do? – Entropy1024 Nov 13 '10 at 14:28
  • 1
    Just to revive an old answer, this answer is wrong. String.substring() take indexes inclusive, exclusive. Therefore, the arguments should be (0, 4) (4, 8) (8, 12). – matt burns Nov 20 '12 at 16:35
6

Or another alternative way using a StringBuilder rather than to split the string in multiple parts and then join them :

String original = "123456789012";
int interval = 4;
char separator = '-';

StringBuilder sb = new StringBuilder(original);

for(int i = 0; i < original.length() / interval; i++) {
    sb.insert(((i + 1) * interval) + i, separator);
}

String withDashes = sb.toString();
TooCool
  • 10,598
  • 15
  • 60
  • 85
Marc Wrobel
  • 644
  • 9
  • 19
1

Alternative way:

String original = "123456789012";
int dashInterval = 4;
String withDashes = original.substring(0, dashInterval);
for (int i = dashInterval; i < original.length(); i += dashInterval) {
    withDashes += "-" + original.substring(i, i + dashInterval);
}

return withDashes;

If you needed to pass strings with lengths that were not multiples of the dashInterval you'd have to write an extra bit to handle that to prevent index out of bounds nonsense.

matt burns
  • 24,742
  • 13
  • 105
  • 107