关于String的相关常见方法

 1 package Stirng类;
 2 /**
 3  * String 常见的相关方法摘要
 4  * @author Administrator
 5  *
 6  */
 7 public class DemoStringMethod {
 8     public static void main(String[] args) {
 9         String s = "hello world";
10         //charAt(int index)  返回指定索引处的char值
11         char c =s.charAt(6);
12         System.out.println(c);//w
13         
14         //compareTo(String anotherString);按字典顺序比较两个字符串
15         //compareToIgnoreCase(String str);忽略大小写比较
16         String s1 = "hello guigu";
17         int result = s.compareTo(s1);
18         System.out.println(result);//16    assic差值
19         int result1 = s1.compareTo(s);
20         System.out.println(result1);//-16
21         
22         //concat(String str)将指定的字符串连接到此字符串的结尾
23         System.out.println(s.concat(s1));//hello worldhello guigu
24         System.out.println(s1.concat(s));//hello guiguhello world
25         
26         //endsWith(String suffix)-----测试此字符串是否以指定的后缀结束
27         //startsWith(String prefix)----测试此字符串是否以指定的前缀开始
28         System.out.println(s.endsWith("rld"));//true
29         System.out.println(s.startsWith("hel"));//true
30         
31         //使用指定的字符集将此String编码为byte序列,并将结果存储到一个新的byte数组中
32         byte [] arr = s.getBytes();
33         System.out.println(arr);
34 //        for(byte qq:arr){
35 //            System.out.println((char)qq);
36 //        }
37         for(int i = 0;i<arr.length;i++){
38             System.out.println((char)arr[i]);
39         }
40         
41         //indexOf(int ch)//返回指定字符在此字符串中第一次出现处的索引
42         System.out.println(s.indexOf("w"));//6
43         System.out.println(s.lastIndexOf("w"));//6
44         
45         //replace(char oldChar,char newChar)
46         //返回一个新的字符串,它是通过用newChar 替换此字符串中出现的所有oldChar得到的
47         System.out.println(s.replace("l", "p"));//hello world------>heppo worpd
48         
49         //toLowerCase()     toUpperCase()  转换大小写
50         System.out.println("AbcdEfG".toLowerCase());
51         System.out.println("AbcdEfG".toUpperCase());
52         
53         //trim()  返回字符串的副本,忽略前后空格
54         System.out.println("   S    D   F    a".trim());
55         
56         
57         String str1 = "hello";
58         String str2 = "hello";
59         
60         String str3 = new String("hello");
61         String str4 = new String("hello");
62         
63         System.out.println(str1==str2);//true
64         System.out.println(str1==str3);//false
65         System.out.println(str3==str4);//false
66         
67         System.out.println(str1.equals(str2));//true
68         System.out.println(str1.equals(str3));//true
69         System.out.println(str3.equals(str4));//true
70         
71         
72         
73     }
74 }
原文地址:https://www.cnblogs.com/wujiwen/p/6288986.html