Android - Format string with mask
I have a product number which I would like to format using a mask.
Example:
String productNumbe开发者_如何学编程r = "0913014316";
String mask = "XX.XXX.XXX.XXX";
How do I get this following output: 09.13.014.316
?
Can I use String.format()
? Or maybe something else on the Android?
Thank you
I think writing this yourself instead of waiting for an answer here would be faster :-)
You could do something like (pseudocode):
StringBuilder out = new StringBuilder();
int j=0;
for (int i = 0; i< mask.lenght ; i++) {
if (mask[i] == 'X') {
out.append(producNumber[j];
j++;
}
else {
out.append('.');
i++;
}
}
return out.toString();
for others who have the same problem, here is full solution:
public String getMaskedText(String rawText, String mask, char variableChar, char constChar) {
StringBuilder out = new StringBuilder();
for (int i = 0, j = 0; i < mask.length() && j < rawText.length(); i++) {
if (mask.charAt(i) == variableChar) {
out.append(rawText.charAt(j));
j++;
} else {
out.append(constChar);
}
}
return out.toString();
}
So you can use it like this:
String result = getMaskedText("123456789", "##-###-###",'#','-');
精彩评论