0

I want to parse latex string to math expression with following code

static string ParseString(List<string> startItems, string input)
{
    foreach (var item in startItems)
    {
        int charLocation = input.IndexOf(item, StringComparison.Ordinal);
        if (charLocation > 0)
        {
            switch (input.Substring(0, charLocation).Last())
            {
                case '{':
                case '+':
                case '-':
                case '*':
                    break;
                default: 
                    input = input.Replace(item, "*" + item); 
                    break;
            }
        }
    }
    return input;
}
static void Main(string[] args)
{
    string ToParse = @"\sqrt{3}\sqrt{3}*4\sqrt{3}";
    ToParse = ParseString(new System.Collections.Generic.List<string> { @"\frac", @"\sqrt" }, ToParse);
    Console.WriteLine(ToParse);
}

I should get before every \sqrt word multiply char.But my program breaks in first \sqrt and cant parse others. Result is

\sqrt{3}\sqrt{3}*4\sqrt{3}

And i want to get

\sqrt{3}*\sqrt{3}*4*\sqrt{3}

Sorry for bad English.

1 Answers1

0

Based on provided example you can do as simple as input = input.Replace(item, "*" + item).TrimStart('*'); (Replace replaces all occurrences of string/char).

As for your code, you have next issues:

  • First inclusion of \sqrt returns charLocation set to 0 (arrays are xero-based in C#), so your check charLocation > 0 evaluates to false, so nothing happens
  • input.Substring(i, l) accepts 2 parameters - start index and length, so it is incorrect to use your charLocation as second parameter(even if you remove previous check, input.Substring(0, charLocation).Last() will end in exception Sequence contains no elements).

So if you want to go through all occurrences and insert symbol based on some logic then you'll need to have some cycle and move start index and calculate length(and also use something else, not Replace). Or you can dive into Regular Expressions.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132