возник вопрос, как посчитать количество символов в строке в формате int

I am a newbie, I have a question, how to count the number of characters in a string in int format and make this number the length of an array

   bool foundPlus = textBox1.Text.Contains("+");
   if (foundPlus == true)
   {

       string[] addition = textBox1.Text.Split('+');

       int a = Convert.ToInt32(int.Parse(addition[0]));
       int b = Convert.ToInt32(int.Parse(addition[1]));

       int result = a + b;

       textBox1.Text = $"= {Convert.ToString(result)}";



   }

In this code, there is a text field textBox1.Text, there is foundPlus thing that checks if there are + in the text field if there are, then an array is created and its length will always be 2 a and b because I use Split which splits the text into two parts a(before the plus) and b(after the plus) and it doesn't care about the other +.

sample robot

1+1+1=2

it is clear that it should be 3


Ответы (1 шт):

Автор решения: AlexanderSt

Try this:

if (!textBox1.Text.Contains('+'))
    return;

int sum = 0;
int num = 0;

foreach (var addition in textBox1.Text.Split('+'))
{
    sum += int.TryParse(addition, out num) ? num : 0;
}

textBox1.Text = $"= {sum}";
→ Ссылка