Since you explicitly mentioned one StringBuilder
, here’s an example:
var mascara = "12****3*59**100*";
var numero = "12345768".ToCharArray();
var mascarr = mascara.Split('*');
var buffer = new StringBuilder();
for (var index = 0; index < mascarr.Length - 1; index++)
{
buffer.Append(mascarr[index] + numero[index]);
}
var result = buffer.ToString();
// Resultado: 1212343559761008
For each asterisk present in the mask, the third line of code will generate an item in the array mascarr
. Thus:
The next block is just a loop between all members of the array, adding the number relative to the loop cursor and adding everything to its object StringBuilder
.
(EDIT: As well mentioned by @Luizvieira in the comments, it is interesting to mention that the last member of the array should be ignored - because it was not itself delimited by an asterisk. So the loop just goes up mascarr.Length - 1
. The original code already had this stipulated value, but this post did not explain the reason.)
Great solution. But it seems to me that the array actually has 1 item more than the number of asterisks (because "*" was used as the delimiter in the separation). It’s just a matter of being precise in the information. : ) P.S.: Incidentally, improvement suggestion: this fact could be used to validate the data before processing, because if by chance the number of characters in
numero
is less than the number of asterisks inmascara
, your loop will generate an error while trying to indexnumero[index]
).– Luiz Vieira
@Luizvieira you are correct about the size of the array - so the loop
for
goes up tomascarr.Length - 1
instead ofmascarr.Length
: The last member of the array should be ignored because it was not itself delimited by an asterisk. As for validation, I also agree - but I thought it would be preferable to have an excerpt of code that only dealt with the main points of the OP issue. Anyway, I appreciate the comments!– OnoSendai
Yes, I didn’t mean that the code is wrong (by the way, your solution is quite clever in my opinion). My comment is more in the sense that the mention in the text practically says that
Split
"generates an item for each asterisk, "and that’s not exactly true. My concern is only that this mention may induce a wrong understanding of the behavior of the method for those who are learning. Sorry for the confusion - I mentioned finding the number of items to ben+1
only to amend the validation suggestion. :)– Luiz Vieira
@Luizvieira No stress, next time I pay the chopp. =)
– OnoSendai