Get number inside of a string and do a loop

做~自己de王妃 提交于 2019-12-13 08:09:19

问题


I want to get a number of a string, and separate the string and the number, and then, do a loop and call a method the number of times the string says. The string has to have this structure: "ABJ3" (Only one number accepted and 3 characters before it)

This is my code, but it repeat hundred of times, I don't know why

            int veces = 0;
            for (int i = 0; i < m.Length; i++)
            {
                if (Char.IsDigit(m[i]))
                    veces = Convert.ToInt32(m[i]);
            }

            if (m.Length == 4)
            {
                for (int i = 0; i <= veces; i++)
                {
                    m = m.Substring(0, 3);
                    operaciones(m, u, t);
                    Thread.Sleep(100);
                }
            }
            operaciones(m,u,t);
            if (u.Length >= 14)
            {
                u = u.Substring(0, 15);
            }

Some help please?


回答1:


You have to convert your m[i] ToString() right now you are sending the char value to Convert.ToInt32 and that is a much higher value (9 = 57 for example)

char t = '9';

int te = Convert.ToInt32(t.ToString());

Console.WriteLine(te);

This gives us a result of 9 but

char t = '9';

int te = Convert.ToInt32(t);

Console.WriteLine(te);

Gives us a result of 57

So you need to change

veces = Convert.ToInt32(m[i]);

to

veces = Convert.ToInt32(m[i].ToString());

Hope it helped.

Best regards //KH.




回答2:


You cannot convert the digits like this. You're overwriting them and taking only the last one. Moreover, you're taking its ASCII code, not digit value. You have to extract all digits first then convert them:

int position = 0;
int veces = 0;
string temp = ""
for (int i = 0; i < m.Length; i++) {
  if (Char.IsDigit(m[i]))
    position = i;
  else
    break;
}
veces = Convert.ToInt32(m.SubString(0, i + 1));

Alternatively, you can use regex instead.



来源:https://stackoverflow.com/questions/22225222/get-number-inside-of-a-string-and-do-a-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!