代码:
- package main
-
- import (
- "fmt"
- )
-
- func main() {
- var str1 = "2"
- var str2 = "11"
- fmt.Println(str1 < str2)
- str1 = "02"
- str2 = "11"
- fmt.Println(str1 < str2)
- }
结果:
- false
- true
总结:
从左到右逐个字符根据ASCII码值的大小来比较。如果要用到字符串比较大小,必须保证位数相同,进制相同。
运行效率比较:
- package main
-
- import (
- "fmt"
- "strconv"
- "time"
- )
-
- func main() {
- timeNow := time.Now().UnixNano()
- fmt.Println(timeNow)
- var str1 = "20191220"
- var str2 = "20191202"
- var result bool
- for i := 0; i < 100000; i++ {
- result = str1 < str2
- }
- timeEnd := time.Now().UnixNano()
- fmt.Println(timeEnd)
- fmt.Println(result, timeEnd-timeNow)
-
-
- timeNow = time.Now().UnixNano()
- fmt.Println(timeNow)
- str1 = "20191220"
- str2 = "20191202"
- for i := 0; i < 100000; i++ {
- num1, _ := strconv.Atoi(str1)
- num2, _ := strconv.Atoi(str2)
- result = num1 < num2
- }
- timeEnd = time.Now().UnixNano()
- fmt.Println(timeEnd)
- fmt.Println(result, timeEnd-timeNow)
- }