昨天面试北京宝兰德,题目不多,40道选择,3到编程,手写程序一直是我的弱项,所以结果就不用说了
最后一道编程题就是比较两个字符串的大小,具体要求记不大清了,大体就是如果v1 > v2 return 1 ,v1 == v2 return 0 ,v1 < v2 return -1
今天早晨起的很晚,也没什么事,顺便将这几次校园招聘的笔试题目总结一下,必考的就是字符串的各种比较题
代码如下
1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 6 String v1 = new String("hello"); 7 String v2 = new String("helloab"); 8 switch(StringUtil(v1,v2)) 9 { 10 case 0 : 11 System.out.println("V1 == V2"); 12 break; 13 case 1: 14 System.out.println("V1 > V2"); 15 break; 16 case -1: 17 System.out.println("V1 < V2"); 18 break; 19 } 20 } 21 22 public static int StringUtil(String v1 ,String v2) 23 { 24 int len = v1.length() <= v2.length() ? v1.length() : v2.length();
// 找到两个字符串的长度中的较小值,如果是较大值下面的比较会出现超出索引异常 25 for(int i = 0; i< len;i++) 26 { 27 if(v1.charAt(i) > v2.charAt(i)) 28 { 29 return 1; 30 } 31 else if(v1.charAt(i) < v2.charAt(i)) 32 { 33 return -1; 34 } 35 else 36 { 37 i++; 38 } 39 }
//在这里说明前len个字符是相等的,下面根据哪个字符串长度大来判断 40 if(v1.length() > v2.length()) 41 { 42 return 1; 43 } 44 else if(v1.length() < v2.length()) 45 { 46 return -1; 47 } 48 else 49 { 50 return 0; 51 } 52 53 } 54 }