Skip to content Skip to sidebar Skip to footer

String Manipulation Insert A Character Every 4th Character

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 s

Solution 1:

Strings="123456789012";
Strings1= s.substring(0, 4);
Strings2= s.substring(4, 8);
Strings3= s.substring(8, 12);

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

substring() Reference

Solution 2:

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

Stringoriginal="123456789012";
intinterval=4;
charseparator='-';

StringBuildersb=newStringBuilder(original);

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

StringwithDashes= sb.toString();

Solution 3:

Alternative way:

Stringoriginal="123456789012";
intdashInterval=4;
StringwithDashes= original.substring(0, dashInterval);
for (inti= 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.

Post a Comment for "String Manipulation Insert A Character Every 4th Character"