Hello Everyone!
In this Kata/Kumite we will work with strings!!
You have to find all chars indexes passed by parameter in a string
and replace them with the index parameter with pad left '0'.
EXAMPLE 1:
sValueReplacer("9182 7391238 91$$$$", 3, '$');
RESULT 1:
9182 7391238 910003
EXAMPLE 2:
sValueReplacer("The counter is ---", 11, '-');
RESULT 2:
"The counter is 011"
using System;
using System.Linq;
using System.Collections.Generic;
public class Test{
static void Main(){
Console.WriteLine(Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));
}
}
public class Replacer{
public static string sValueReplacer(string source, int index, char char_to_replace)
{
string res = source;
try
{
if (!string.IsNullOrEmpty(char_to_replace.ToString()))
{
if (res.Contains(char_to_replace.ToString()))
{
// Get ALL Indexes position of character
var Indexes = GetIndexes(res, char_to_replace.ToString());
int max = GetMaxValue(Indexes.Count);
while (index >= max)
{
index -= max;
}
var new_value = index.ToString().PadLeft(Indexes.Count, '0');
for (int i = 0; i < Indexes.Count; i++)
{
res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());
}
}
}
}
catch (Exception)
{
res = source;
}
return res;
}
private static List<int> GetIndexes(string mainString, string toFind)
{
var Indexes = new List<int>();
for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1))
{
// for loop end when i=-1 (line.counter not found)
Indexes.Add(i);
}
return Indexes;
}
private static int GetMaxValue(int numIndexes)
{
int max = 0;
for (int i = 0; i < numIndexes; i++)
{
if (i == 0)
max = 9;
else
max = max * 10 + 9;
}
return max;
}
}