Java基础知识强化35:String类之String的其他功能

1. String类的其他功能:

(1)替换功能:

String replace(char old, char new)
String replace(String old,String new

 

(2)去除字符串两端的空格

String trim()

(3)按照字典顺序比较两个字符串

int compareTo(String str)
int compareToIgnoreCase(String str)

 

2. 案例演示:

 1 package cn.itcast_06;
 2 
 3 /*
 4  * String类的其他功能:
 5  * 
 6  * 替换功能:
 7  * String replace(char old,char new)
 8  * String replace(String old,String new)
 9  *
10  * 去除字符串两空格    
11  * String trim()
12  * 
13  * 按字典顺序比较两个字符串  
14  * int compareTo(String str)
15  * int compareToIgnoreCase(String str)
16  */
17 public class StringDemo {
18     public static void main(String[] args) {
19         // 替换功能
20         String s1 = "helloworld";
21         String s2 = s1.replace('l', 'k');
22         String s3 = s1.replace("owo", "ak47");
23         System.out.println("s1:" + s1);
24         System.out.println("s2:" + s2);
25         System.out.println("s3:" + s3);
26         System.out.println("---------------");
27 
28         // 去除字符串两空格
29         String s4 = " hello world  ";
30         String s5 = s4.trim();
31         System.out.println("s4:" + s4 + "---");
32         System.out.println("s5:" + s5 + "---");
33 
34         // 按字典顺序比较两个字符串
35         String s6 = "hello";
36         String s7 = "hello";
37         String s8 = "abc";
38         String s9 = "xyz";
39         System.out.println(s6.compareTo(s7));// 0
40         System.out.println(s6.compareTo(s8));// 7
41         System.out.println(s6.compareTo(s9));// -16
42     }
43 }

运行效果如下:

posted on 2015-09-19 17:41  鸿钧老祖  阅读(169)  评论(0编辑  收藏  举报

导航