我们有这个编码练习来手动实现.Net
的Int.Parse()方法我没有得到他们'正确'解决方案的工作方式。但我记得它包括将角色分解为第十,百分之一......
我找到了一个用Java函数完成的解决方案。有人可以向我解释如何将它乘以数字将字符串解析为int吗?
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
答案 0 :(得分:1)
这是使用Linq的方式之一,
string st = "1234785";
int i = 0;
int counter = 0;
st.All(x => {
if (char.IsDigit(x))
{
i += (int)(char.GetNumericValue(x) * Math.Pow(10, (st.Length - counter - 1)));
}
counter++;
return true;
});
之后,i = 1234785。
如果你输入一些类似“hello”的字符串,如果你传递字符串“Hello 123”,它将返回0给你 那么它会让你回归123。
答案 1 :(得分:1)
实际上,这不是完成家庭工作的地方: - )
然而,我记得,分析我的拳头节目,以了解“如何做这样的事情”。 在以后的某些时候,我总是习惯将外国代码重构成我能理解的小块。
所以,对于上面的代码片段,这可能是:
public static int myStringToInteger(String str) {
int answer = 0;
int factor = 1;
// Iterate over all characters (from right to left)
for (int i = str.length() - 1; i >= 0; i--) {
// Determine the value of the current character
// (I guess this is the trick you were missing
// We extract a single character, subtract the
// ASCII value the character '0', getting the "distance"
// from zero. So we converted a single character into
// its integer value)
char currentCharacter = str.charAt( i );
int value = currentCharacter - '0';
// Add the value of the character at the right place
answer += value * factor;
// Step one place further
factor *= 10;
}
return answer;
}
答案 2 :(得分:0)
我们假设它得到以下字符串:"01234"
;
答案实际上是迭代值的总和,从0开始。 因子是你乘以第n位的乘数。
这样做,基本上是:
answer = 0
factor = 1
answer = answer + (4 * 1) = 0 + 4 = 4;
factor = 10;
answer = answer + (3 * 10) = 4 + 30 = 34;
factor = 100;
answer = answer + (2 * 100) = 34 + 200 = 234;
factor = 1000;
answer = answer + (1 * 1000) = 234 + 1000 = 1234;
factor = 1000;
answer = answer + (0 * 10000) = 1234 + 0 = 1234;
当然,当字符串由超过普通数字的字符串组成时,您需要注意这种情况。