演算法筆記_084:藍橋杯練習 11-1實現strcmp函數(Java)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.