Kotlin에서 String을 Long으로 변환하는 방법?
코 틀린 챌린지가 시작되었습니다.
모든 작업은 콘솔에서 매개 변수를 읽고 콘솔에 출력을 기록하여 자동 확인이 가능한 콘솔 프로그램을 작성해야합니다.
코 틀린의 주요 방법은 다음과 같습니다
fun main(args: Array<String>): Unit {
//do something
}
작업의 입력 매개 변수는 대부분 숫자로 해석해야합니다. 그래서 Long.valueOf(String s)
방금 붙어있는 것과 같은 방법이 없기 때문에 . String을 Long으로 변환 할 수 없으며 부끄러워합니다.
1. string.toLong()
문자열을 [Long] 숫자로 구문 분석하고 결과를 리턴합니다.
@throws NumberFormatException 문자열이 유효한 숫자 표현이 아닌 경우.
2. string.toLongOrNull()
문자열을 [Long] 숫자로 구문 분석하고 결과
null
가 문자열이 유효한 숫자 표현이 아닌 경우를 리턴합니다 .
삼. str.toLong(10)
문자열을 [Long] 숫자로 구문 분석하고 결과를 리턴합니다.
@throws NumberFormatException 문자열이 유효한 숫자 표현이 아닌 경우.
@throws IllegalArgumentException [radix]가 문자열 대 숫자 변환에 유효한 기수가 아닌 경우.
public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))
4. string.toLongOrNull(10)
문자열을 [Long] 숫자로 구문 분석하고 결과
null
가 문자열이 유효한 숫자 표현이 아닌 경우를 리턴합니다 .@throws IllegalArgumentException [radix]가 문자열 대 숫자 변환에 유효한 기수가 아닌 경우.
public fun String.toLongOrNull(radix: Int): Long? {...}
5. java.lang.Long.valueOf(string)
public static Long valueOf(String s) throws NumberFormatException
String
해당 확장 방법이 있습니다.
"10".toLong()
확장 메소드는 String
다른 기본 유형으로 구문 분석 할 수 있습니다. 아래 예 :
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
"10".toInt()
"10".toLong()
참고 : 언급 한 답변 jet.String
은 구식입니다. 현재 Kotlin (1.0)은 다음과 같습니다.
String
Kotlin의 모든 사용자 는 이미 호출 할 수있는 확장 기능을 가지고 있습니다 toLong()
. 특별한 것이 필요하지 않습니다. 그냥 사용하십시오.
에 대한 모든 확장 기능String
이 문서화되어 있습니다. API 참조 에서 표준 lib에 대한 다른 것을 찾을 수 있습니다.
흥미 롭군. 다음과 같은 코드 :
val num = java.lang.Long.valueOf("2");
println(num);
println(num is kotlin.Long);
이 출력을 만듭니다.
2
true
Kotlin 은이 경우 java.lang.Long
긴 프리미티브에서 kotlin.Long
자동으로 변환 합니다. 따라서 솔루션이지만 java.lang 패키지 사용없이 도구를 보게되어 기쁩니다.
실제로 '길이'도 확인해야하는 시간의 90 %가 유효하므로 다음이 필요합니다.
"10".toLongOrNull()
기본 유형의 각 'toLong'에 대해 'orNull'이 있으며 Kotlin과 함께 유효하지 않은 사례를 관리 할 수 있습니까? 관용구.
string.toLong ()
string
변수는 어디에 있습니까 ?
NumberFormatException
파싱하는 동안 처리하고 싶지 않은 경우
var someLongValue=string.toLongOrNull() ?: 0
Kotlin Programming Language에서 문자열을 Long으로 변환하는 방법은 5 가지가 있으며 다음과 같습니다.
- string.toLong ()
- string.toLongOrNull ()
- string.toLong (10)
- string.toLongOrNull (10)
- java.lang.Long.valueOf (문자열)
Refer docs for explanation in detail.
One good old Java possibility what's not mentioned in the answers is java.lang.Long.decode(String)
.
Decimal Strings:
Kotlin's String.toLong()
is equivalent to Java's Long.parseLong(String)
:
Parses the string argument as a signed decimal long. ... The resulting long value is returned, exactly as if the argument and the radix 10 were given as arguments to the
parseLong(java.lang.String, int)
method.
Non-decimal Strings:
Kotlin's String.toLong(radix: Int)
is equivalent to Java's eLong.parseLong(String, int)
:
Parses the string argument as a signed long in the radix specified by the second argument. The characters in the string must all be digits of the specified radix ...
And here comes java.lang.Long.decode(String)
into the picture:
Decodes a String into a Long. Accepts decimal, hexadecimal, and octal numbers given by the following grammar: DecodableString:
(Sign) DecimalNumeral | (Sign) 0x HexDigits | (Sign) 0X HexDigits | (Sign) # HexDigits | (Sign) 0 OctalDigits
Sign: - | +
That means that decode
can parse Strings like "0x412"
, where other methods will result in a NumberFormatException
.
val kotlin_toLong010 = "010".toLong() // 10 as parsed as decimal
val kotlin_toLong10 = "10".toLong() // 10 as parsed as decimal
val java_parseLong010 = java.lang.Long.parseLong("010") // 10 as parsed as decimal
val java_parseLong10 = java.lang.Long.parseLong("10") // 10 as parsed as decimal
val kotlin_toLong010Radix = "010".toLong(8) // 8 as "octal" parsing is forced
val kotlin_toLong10Radix = "10".toLong(8) // 8 as "octal" parsing is forced
val java_parseLong010Radix = java.lang.Long.parseLong("010", 8) // 8 as "octal" parsing is forced
val java_parseLong10Radix = java.lang.Long.parseLong("10", 8) // 8 as "octal" parsing is forced
val java_decode010 = java.lang.Long.decode("010") // 8 as 0 means "octal"
val java_decode10 = java.lang.Long.decode("10") // 10 as parsed as decimal
To convert a String
to Long
(that represents a 64-bit signed integer) in Kotlin 1.3 is quite simple.
You can use any of the following three methods:
val number1: Long = "789".toLong()
println(number1) // 789
val number2: Long? = "404".toLongOrNull()
println("number = $number2") // number = 404
val number3: Long? = "Error404".toLongOrNull()
println("number = $number3") // number = null
val number4: Long? = "111".toLongOrNull(2)
println("numberWithRadix(2) = $number4") // numberWithRadix(2) = 7
Actually, there are several ways:
Given:
var numberString : String = "numberString"
// number is the Long value of numberString (if any)
var defaultValue : Long = defaultValue
Then we have:
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString is a valid number ? | true | false |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLong() | number | NumberFormatException |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLongOrNull() | number | null |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLongOrNull() ?: defaultValue | number | defaultValue |
+—————————————————————————————————————————————+——————————+———————————————————————+
참고URL : https://stackoverflow.com/questions/19519468/how-to-convert-string-to-long-in-kotlin
'Programing' 카테고리의 다른 글
'='작업에 대한 데이터 정렬 (utf8_unicode_ci, IMPLICIT)과 (utf8_general_ci, IMPLICIT)의 잘못된 조합 (0) | 2020.06.24 |
---|---|
Visual Studio 2015에서 C # 6 지원을 비활성화하려면 어떻게합니까? (0) | 2020.06.24 |
Eclipse에서 Tomcat 로그 파일을 어디에서 볼 수 있습니까? (0) | 2020.06.23 |
string.split-여러 문자 구분 기호로 (0) | 2020.06.23 |
Vim에서 큰 따옴표 안의 모든 것을 어떻게 삭제합니까? (0) | 2020.06.23 |