简体   繁体   English

如何在数组中查找整数的长度

[英]How to find the length of an integer in an array

I want to be able to find the length of a certain value within an array. 我希望能够找到数组中某个值的长度。 I have tried: 我努力了:

String.valueOf(array[arrayValue])

but I am unable to see if it is < a certain number within an if statement. 但我无法在if语句中查看它是否<特定数字。 For example I want to see if the length of the certain value at hand is less than four. 例如,我想看看手边的某个值的长度是否小于四。 I have something like this right now: 我现在有这样的事情:

if(String.valueOf(array[arrayValue] < 4)){
    //does something
}

However it says that I cannot use the "<" sign for some reason. 但是它说由于某种原因我不能使用“ <”符号。 Does anyone know how I would successfully be able to do this? 有谁知道我将如何成功做到这一点?

What you want is 你想要的是

if(Integer.toString(array[arrayValue]).length()>4)

This takes the arrayValue th element from your array, converts it to a String , finds the length, then compares that to 4 . 这从数组中获取arrayValue th元素,将其转换为String ,找到长度,然后将其与4进行比较。

Your current code is taking the arrayValue th element from your array, comparing it to 4 , and then converting the result of the comparison true or false to a String: "true" or "false" . 您当前的代码是从数组中获取arrayValue th元素,将其与4进行比较,然后将比较结果truefalse转换为String: "true""false" It is then trying to pass the String to the if clause, which only takes boolean, so its throwing an error. 然后,它尝试将String传递给if子句,该子句仅使用布尔值,因此会引发错误。

The cause of the code not being compiled is already pointed out by k_g . k_g已指出未编译代码的原因。
However, your statement 但是,你的陈述

it says that I cannot use the "<" sign for some reason 它说由于某种原因我不能使用“ <”符号

is not entirely true: String.valueOf(array[arrayValue] < 4) is perfectly valid, but it returns a String, and that's not possible as condition in an if-statement. 并非完全正确: String.valueOf(array[arrayValue] < 4)完全有效,但是它返回一个String,并且不能作为if语句中的条件。

Getting the 'length' of an integer 获取整数的“长度”

To calculate the length – I prefer to say 'width' – of an integer, there are two approaches: 要计算整数的长度(我更喜欢说“宽度”),有两种方法:

  • One might want to convert the integer to a string and getting the length of the string, see k_g 's answer, but conversion to string is expensive . 可能需要将整数转换为字符串并获取字符串的长度,请参见k_g的答案,但转换为字符串的成本很高
  • A better approach might be this: 更好的方法可能是这样的:
    Repeatedly divide the given value by 10 until it drops below 1: 重复将给定值除以10,直到其降至1以下:

     public static int getWidth(int value) { int i = 0; while (value > 0) { value /= 10; i++; } return i; } 

    It avoids int-to-string conversion, making it approximately 5.6 times faster . 它避免了int到字符串的转换,使其转换速度大约快5.6倍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM