java string.compare实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java string.compare实现相关的知识,希望对你有一定的参考价值。

package com.pg.cmpr;

public class cmprStringTest {

	public static void main(String[] args) {
		String s1 = "abcdfffff";
		String s2 = "abce";
		String s3 = "abcd";
		System.out.println("Our impementation-==---------------==-");
		System.out.println(s1.compareTo(s2));
		System.out.println(s1.compareTo(s3));
		System.out.println("Standart implementation-==---------------==-");
		System.out.println(compareString(s1, s2));
		System.out.println(compareString(s1, s3));
	}
	
	public static int compareString (String s1, String s2){

		char[] sarr1 = s1.toCharArray();
		char[] sarr2 = s2.toCharArray();
		for (int i = 0; i < Math.min(sarr1.length, sarr2.length); i++){
			if (sarr1[i] != sarr2[i]) return sarr1[i] - sarr2[i] ;
		}
		return sarr1.length - sarr2.length;
		
	}
}

以上是关于java string.compare实现的主要内容,如果未能解决你的问题,请参考以下文章

C#中String的静态方法Compare(str1,str2)比较字符串大小

C#字符串比较方法Compare()

C++ string.compare()

string::compare 多余的参数?

844. Backspace String Compare

LeetCode 844. Backspace String Compare