標籤:blog logs color else 相等 ring break print ati
目錄
1 問題描述
2 解決方案
1 問題描述問題描述 自己實現一個比較字串大小的函數,也即實現strcmp函數。函數:int myStrcmp(char *s1,char *s2) 按照ASCII順序比較字串s1與s2。若s1與s2相等返回0,s1>s2返回1,s1<s2返回-1。具體來說,兩個字串自左向右逐個字元相比(按ASCII值大小相比較),直到出現不同的字元或遇‘\0‘為止(注意‘\0‘值為0,小於任意ASCII字元)。如:
"A"<"B"
"a">"A"
"computer">"compare"
"hello"<"helloworld"範例輸出資料規模和約定 字串長度<100。
2 解決方案
具體代碼如下:
import java.util.Scanner;public class Main { public void printResult(String A, String B) { int lenA = A.length(); int lenB = B.length(); if(lenA < 1 || lenB < 1) return; char[] arrayA = A.toCharArray(); char[] arrayB = B.toCharArray(); int i = 0, j = 0; int judge = 10000; while(i < lenA && j < lenB) { judge = arrayA[i++] - arrayB[j++]; if(judge != 0) break; } if(judge > 0 && judge != 10000) { System.out.println("1"); } else if(judge < 0) { System.out.println("-1"); } else { int tempi = lenA - i; int tempj = lenB - j; if(tempi == tempj) { System.out.println("0"); } else if(tempi > tempj) { System.out.println("1"); } else if(tempi < tempj) { System.out.println("-1"); } } return; } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); String A = in.nextLine(); String B = in.nextLine(); test.printResult(A, B); }}
演算法筆記_084:藍橋杯練習 11-1實現strcmp函數(Java)