记split函数的一个坑

今天参加美团面试,讲了半个多小时的面经题目后面试官出了一道手写算法题。

题目很简单,给一个字符串,形如“3.1.0.1”的版本号,再给一个格式正确的版本号,然后判断两个字符串的大小。

我一看非常简单啊,啪的一下就写完了,其中用了split函数切割字符串,但没想到运行结果不对。

| ^ $ * . ( ) \ /等都是正则表达式的一部分,只能通过前面加上\进行转义。注意\要用三个\\,也就是split(“\\\”)。

事后我百思不得其解,最终上网查发现split接收“.”做参数需要转义符号,真是被坑惨了。

import java.io.IOException;
import java.util.*;

class Main {
    public static void main(String[] args) throws IOException {
        @SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine(),str2 = sc.nextLine();
        String[] arr1 = str1.split("\\."),arr2 = str2.split("\\.");
        int len1 = arr1.length,len2 = arr2.length,len = len1>len2?len2:len1,res=0;
        System.out.println(len1+" "+len2);
        for(int i=0;i<len;i++)
        {
        	int num1 = Integer.parseInt(arr1[i]),num2 = Integer.parseInt(arr2[i]);
        	if(num1 > num2)
        	{
        		res = 1;
        		break;
        	}
        	else if(num1 < num2)
        	{
        		res = -1;
        		break;
        	}
        }
        if(res == 0)
        {
        	if(len1 > len2)
        		res = 1;
        	else if(len1 < len2)
        		res = -1;
        }
        System.out.println(res);
    }
}

  当然用正则表达式就没这问题了,代码写少了问题真的很严重。。。

posted @ 2021-04-19 20:37  梵蒂冈宝石  阅读(139)  评论(0编辑  收藏  举报