字符串转数字

int ConverStringToInt(string content)

{

int i = content.length;

int number = 0;

foreach(char c in content)

{

if(CheckIsNumber(c))

{

number += (c - '0') * 10^i;

}

i -= 1;

}

return number;

}


bool CheckIsNumber(char c)

{

if(c -'0' < 9 && c -'0' >= 0) return true;

else return false;

}



以上的代码是过年前写的,随手在博客里敲出来的,是毕业时找工作时候的面试题

当时没答出来,因为当时没学过c#

后来有天突然想起来就写了出来,没用编辑器也,也没测试过

今天整理blog的时候,测试了一下

果然是有问题的

1.10^i,不是10的平方.....果然是被误导了啊,^我记得是异或的2进制运算

2.数组的length返回的数字不能直接作为平方用,会多一位,比如6位的字符串,10的6次方是10000000,多了一位

3.'c' -'0'的数值范围不是0到9,是0到10.测试的时候发现的,9居然不会出现,才明白是9没有被算作数字对待


以下是修改过的代码,经测试没有问题

果然代码这种东西,光靠自己写不写啊,还需要ide的自动提示功能和测试才能正常运作啊

ps:最后又发现一个问题,如果位数太多的话一定会出现结果错误




    public static int ConverStringToInt(string content)
    {
        int i = content.ToCharArray().Length -1;
        int number = 0;
        foreach(char c in content)
        {
            if(CheckIsNumber(c))
            {
                number += (c - '0') * (int)Mathf.Pow(10f,i);
            } 
            i -= 1;
        }
        return number;
    }
    
    private static bool CheckIsNumber(char c)
    {
        if(c -'0' < 10 && c -'0' >= 0return true;
        else return false;
    }


附带一个unity的编辑器脚本,可以用来测试上面的代码

unity的基本其实与编辑器结合起来,才能多快好省的完成工作

这一点是最近领悟出来的

有精力的同学不妨都学学编辑器脚本的写法


using UnityEngine;
using UnityEditor;
using System.Collections;

public class StringToIntEditor : EditorWindow {

    // Use this for initialization
    [MenuItem("Damage/StringToInt")]
    static void Apply () {
        StringToIntEditor window = EditorWindow.GetWindow<StringToIntEditor>();
        window.Show();
    }

    string s;
    void OnGUI()
    {
        s = EditorGUILayout.TextField("Input",s);
        if(GUILayout.Button("Convert"))
        {
            Debug.Log(StringToInt.ConverStringToInt(s).GetType());
            Debug.Log(StringToInt.ConverStringToInt(s));
            
        }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值