Topic: 初学 java 贴个 比较两个字符串的方法

  Print this page

1.初学 java 贴个 比较两个字符串的方法 Copy to clipboard
Posted by: chaostring
Posted on: 2007-11-15 19:57

/*
* This class is to compare two strings.
*/

package comparestring;

/**
* This class contains a method to compare two strings
* @author Chaotring
*/
public class CompareString {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String s1 = "wel";
String s2 = "wel";
System.out.println(compStrings(s1,s2));

}

public static boolean compStrings(String str1, String str2){

/* use equals() */
//return str1.equals(str2)? true: false;

/* use compareTo() */
//return str1.compareTo(str2)==0? true: false;

/* use getChars() */
int l1 = str1.length();
int l2 = str2.length();
char[] c1 = new char[l1];
char[] c2 = new char[l2];
boolean big = false;

if(l1==l2){
str1.getChars(0, l1, c1, 0);
str2.getChars(0, l2, c2, 0);
for(int i = 0; i < l1; i++ ){
if(c1[i] != c2[i]){
break;
}else{
big = true;
}

}
}
return big;

}

}

2.Re:初学 java 贴个 比较两个字符串的方法 [Re: chaostring] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2007-11-16 18:07

maybe equals() is the most frequently used one. I never use compareTo and use gerChars() to compare the equality of two Strings.

3.Re:初学 java 贴个 比较两个字符串的方法 [Re: chaostring] Copy to clipboard
Posted by: chaostring
Posted on: 2007-11-16 19:01

Thanks for your comments. I do agree with you that equals() is much more convenient. I am a freshman on Java, so I try to use these methods for exercise.

Smile

4.Re:初学 java 贴个 比较两个字符串的方法 [Re: chaostring] Copy to clipboard
Posted by: Cappuccino
Posted on: 2007-11-16 23:38

chaostring wrote:
Thanks for your comments. I do agree with you that equals() is much more convenient. I am a freshman on Java, so I try to use these methods for exercise.

Smile


1. 建议你除了自己尝试以外还可以看看String的源代码,更有帮助一些。
2. 譬如上面你提到的equals方法,如果是采用从后往前的方式循环,是不是在大多数情况下都会更快^_^

5.Re:初学 java 贴个 比较两个字符串的方法 [Re: Cappuccino] Copy to clipboard
Posted by: chaostring
Posted on: 2007-11-17 12:02

Cappuccino wrote:
1. 建议你除了自己尝试以外还可以看看String的源代码,更有帮助一些。
2. 譬如上面你提到的equals方法,如果是采用从后往前的方式循环,是不是在大多数情况下都会更快^_^


谢谢你


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923