String类的compareTo()和compareToIgnoreCase()

compareTo()的返回值是int,它是先比较对应字符的大小(ASCII码顺序)

1、如果字符串相等返回值0

2、如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的差值(ascii码值)(负值代表:前字符串的值小于后字符串,正值代表:前字符串大于后字符串)

3、如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方全比较完,这时就比较字符的长度. 

compareToIgnoreCase()方法是不区分大小写,返回值是int,比较方式与compareTo()相同

  1. String s1 = "adger";
  2. String s2 = "adgerfa";
  3. String s3 = "ADGER";
  4. String s4 = "adher";
  5. System.out.println(s1.compareTo(s2));//-2
  6. System.out.println(s1.compareTo(s3));//32
  7. System.out.println(s1.compareToIgnoreCase(s3));//0
  8. System.out.println(s3.compareToIgnoreCase(s4));//-1

应用:不分大小写,比较字符串的大小,按照从小到大排序

  1. package interview;
  2. import java.util.Scanner;
  3. /**
  4. * 比较输入字符串的大小:不分大小写,按照字符串的大小排序
  5. * String类的compareToIgnoreCase()方法
  6. * @author USER
  7. *
  8. */
  9. public class TestCompareTo {
  10. public static void main(String[] args) {
  11. Scanner in = new Scanner(System.in);
  12. String string = in.nextLine();
  13. String[] s = string.split(" ");
  14. for (int i = 0; i < s.length-1; i++) {
  15. for (int j = i+1; j < s.length; j++) {
  16. if (s[i].compareToIgnoreCase(s[j]) > 0) {
  17. String temp = s[i];
  18. s[i] = s[j];
  19. s[j] = temp;
  20. }
  21. }
  22. }
  23. for (int i = 0; i < s.length; i++) {
  24. System.out.print(s[i]+" ");
  25. }
  26. }
  27. }
  28. //测试
  29. //输入:fas rew ada ADE FAA re bci def BCr aC Bc
  30. //输出:aC ada ADE Bc bci BCr def FAA fas re rew


				<script>
					(function(){
						function setArticleH(btnReadmore,posi){
							var winH = $(window).height();
							var articleBox = $("div.article_content");
							var artH = articleBox.height();
							if(artH > winH*posi){
								articleBox.css({
									'height':winH*posi+'px',
									'overflow':'hidden'
								})
								btnReadmore.click(function(){
									if(typeof window.localStorage === "object" && typeof window.csdn.anonymousUserLimit === "object"){
										if(!window.csdn.anonymousUserLimit.judgment()){
											window.csdn.anonymousUserLimit.Jumplogin();
											return false;
										}else if(!currentUserName){
											window.csdn.anonymousUserLimit.updata();
										}
									}
									
									articleBox.removeAttr("style");
									$(this).parent().remove();
								})
							}else{
								btnReadmore.parent().remove();
							}
						}
						var btnReadmore = $("#btn-readmore");
						if(btnReadmore.length>0){
							if(currentUserName){
								setArticleH(btnReadmore,3);
							}else{
								setArticleH(btnReadmore,1.2);
							}
						}
					})()
				</script>
				</article>
posted @ 2018-12-08 17:55  学不死的程序员  阅读(1182)  评论(0编辑  收藏  举报