How to get two number from a string and convert to int in one variable?

只谈情不闲聊 提交于 2019-12-25 06:37:37

问题


I'm trying to finish up my homework and this is the last thing I couldn't figure it out since this afternoon.

Say for example I have string in the array like this ABCD24EFG and I want to get that number 24 in a variable that I initialize which type is int

I can do it with one single number and convert it like this

number_holder = array_name[4] - '0';

and I will get 2 in the number_holder but how can I get the whole like 24 and convert them into int type?


回答1:


You can use this logic.

number_holder=array_name[4] - '0';
number_holder=number_holder*10 + (array_name[5] - '0');

This way you can also handle array values like ABCD243EFG, ABCD2433EFG ...

ASCII value for integers 0-9 are 48 - 57 ..So use this for finding integers in array.

   number_holder=0;
   For (int i=0;i<arraylength;i++) 
    {
        if(array[i]<58 && array[i]>47)
        number_holder=number_holder*10+array[i] - '0';
    }    

You will have your result in number_holder.




回答2:


You can use the famous algorithm

n = 0
while (char = nextchar()) {
  n = n*10 + digit(char)
}

in pseudo language




回答3:


Try

    number_holder_1 = array_name[4] - '0';
    number_holder_2 = array_name[5] - '0';

You will get both number. And perform

number = number_holder_1  * 10 + number_holder_2 ;

If the number must not be 2 digits , then you can use a for loop to get the required number.



来源:https://stackoverflow.com/questions/10629612/how-to-get-two-number-from-a-string-and-convert-to-int-in-one-variable

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