Home > Software engineering >  Is there a way to replace the numbers in a string with the word equivalencies?
Is there a way to replace the numbers in a string with the word equivalencies?

Time:10-26

So I have a string that has some numbers in it. This string is going to be specified by the user and therefore, must be able to detect the numbers in the string and change them into the word equivalent. This is what I have so far:

string[] numwords = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
string sample = "Hello MY naMe is Joe Bloggs 1234567 :-)";
for(int x=0; x<nums.Length; x  )
{
 if (sample.Contains(Convert.ToString(nums[x])))
    {
        int index1 = sample.IndexOf(Convert.ToString(nums[x]));
        sample = sample.Remove(sample[index1],1 );
        sample = sample.Insert(sample[index1], Convert.ToString(numwords[x]));
    }
    
}
Console.WriteLine(sample);

I am getting this error: System.ArgumentOutOfRangeException: 'Index and count must refer to a location within the string. Arg_ParamName_Name'

CodePudding user response:

You can simply use string.Replace:

string sample = "Hello MY naMe is Joe Bloggs 1234567 :-)";
for(int i = 0; i < nums.Length; i  )
{
    sample = sample.Replace(nums[i].ToString(), numwords[i]);
}

Result: Hello MY naMe is Joe Bloggs onetwothreefourfivesixseven :-)

CodePudding user response:

I suggest using Regular Expressions to match and transform the numbers:

using System.Linq;
using System.Text.RegularExpressions;

...

string[] numwords = { 
  "zero", "one", "two", "three", "four", "five", 
  "six", "seven", "eight", "nine", "ten" };

string sample = "Hello MY naMe is Joe Bloggs 1234567 :-)";

var result = Regex.Replace(
  sample,
 "[0-9] ", m =>
  string.Join(", ", m.Value.Select(c => numwords[c - '0'])));

Console.Write(result);

Output:

Hello MY naMe is Joe Bloggs one, two, three, four, five, six, seven :-)
  • Related