Lanqiao Cup ADV-227 11-1 implements strcmp function java

Problem-solving ideas

compareTo

parameter

  • o  - The object to be compared.

  • anotherString  -the string to be compared.

return value

The return value is an integer, which is to compare the size of the corresponding character (ASCII code order), if the first character of the first character and parameter ranges, end comparator, returns the length between their difference , if the first If a character is equal to the first character of the parameter, the second character is compared with the second character of the parameter, and so on, until the compared character or the compared character ends.

  • If the parameter string is equal to this string, the return value is 0;
  • If the string is less than the string parameter, a value less than 0 is returned;
  • If the string is greater than the string parameter, a value greater than 0 is returned.

Instance

public class Test {
 
    public static void main(String args[]) {
        String str1 = "Strings";
        String str2 = "Strings";
        String str3 = "Strings123";
 
        int result = str1.compareTo( str2 );
        System.out.println(result);
      
        result = str2.compareTo( str3 );
        System.out.println(result);
     
        result = str3.compareTo( str1 );
        System.out.println(result);
    }
}
/*
以上程序执行结果为:

0
-3
3
*/

 

Reference Code

package 实现strcmp函数;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
	Scanner sr = new Scanner(System.in);
	String s1 = sr.next();
	String s2 = sr.next();
	int def = s1.compareTo(s2);
	if (def > 0) {
		System.out.println(1);
	}else if (def < 0 ) {
		System.out.println(-1);
	}else {
		System.out.println(0);
	}
}
}

 

Guess you like

Origin blog.csdn.net/qq_40185047/article/details/114645801