藍橋杯試題 算法訓練 字符串比較

試題 算法訓練 字符串比較

資源限制
時間限制:1.0s 內存限制:256.0MB
問題描述
  strncmp函數的原型爲:int strncmp(char *s, char *t, int n);,其功能是比較字符串s和t的前n個字符。如果s<t,返回-1;如果s=t,返回0;如果s>t,返回1。請自己編程實現該函數,並編寫一個程序來測試其正確性。
  輸入格式:輸入有三行,第一行爲字符串s,第二行爲字符串t,第三行爲整數n。
  輸出格式:輸出只有一個整數,即比較結果。
輸入輸出樣例
樣例輸入
world
word
4
樣例輸出
1

import java.util.Scanner;


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String t = sc.nextLine();
        int num = sc.nextInt();
        strncmp(s,t,num);
    }

    public static void strncmp(String s, String t, int num){
        char[] s_char = s.toCharArray();
        char[] t_char = t.toCharArray();
        for (int i = 0; i < num; i++) {
            if (s_char[i]>t_char[i]){
                System.out.println(1);
                break;
            }else if (s_char[i]<t_char[i]){
                System.out.println(-1);
                break;
            }
            if (i==num-1 && s_char[i]==t_char[i]){
                System.out.println(0);
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章