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' >= 0) return 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));
}
}
}