String的經常使用方法

package package1;

public class StringDemo {
public static void main(String[] args) {
	String content="Hello,myfriend, you are my best friend";
	//charAt(2)方法返回指定索引
	System.out.println(content.charAt(2));
	//字符串進行比較--返回整數
	System.out.println(content.compareTo("hello"));
	//字符串鏈接
	content=content.concat("I am zhangsan");
	//content=content+"I am zhangsan";
	System.out.println(content);
	//判斷是否以friend爲結尾,返回true或false
	System.out.println(content.endsWith("friend"));
	//判斷是否以hello爲開頭,返回true或false
	System.out.println(content.startsWith("Hello"));
	//判斷是否包含這個字符串
	System.out.println(content.contains("my"));
	//比較兩個字符串是否相等
	String s1="abc";
	String s2="abc";
	System.out.println(s1==s2);
	System.out.println(s1.equals(s2));
	String s3=new String("abc");
	String s4=new String("abc");
	System.out.println(s3==s4);
	System.out.println(s3.equals(s4));
	//忽略大小寫
	System.out.println(content.equalsIgnoreCase(content));
	//輸出字符串出現的下標
	System.out.println(content.indexOf("o"));
	//最後出現的字符串的位置
	System.out.println(content.lastIndexOf("o"));
	//從座標5開始算起日後找o出現的位置
	System.out.println(content.indexOf("o",5));
	//計算字符串的長度(不一樣於數組,數組的length是屬性),length()是方法
	System.out.println(content.length());
	//替換字符串(把Hello中的e替換成a)
	System.out.println(content.replace('e','a'));
	//拆分字符串
	String[] array=content.split(" ");//注意按照空格來分割
	System.out.println(array.length);
	for(int i=0;i<array.length;i++) {
		System.out.println(array[i]);
	}
	//截取字符串,從下標爲5開始截取,得到一個新的字符串
	System.out.println(content.substring(5));
	//截取字符串,從下標爲5開始截取,到9結束
	System.out.println(content.substring(5, 9));
	//大小寫轉換
	System.out.println(content.toLowerCase());
	System.out.println(content.toUpperCase());
}
}
結果:
l
-32
Hello,myfriend, you are my best friendI am zhangsan
false
true
true
true
true
false
true
true
4
17
17
51
Hallo,myfriand, you ara my bast friandI am zhangsan
8
Hello,myfriend,
you
are
my
best
friendI
am
zhangsan
,myfriend, you are my best friendI am zhangsan
,myf
hello,myfriend, you are my best friendi am zhangsan
HELLO,MYFRIEND, YOU ARE MY BEST FRIENDI AM ZHANGSAN
案例:
package package1;

public class Demo6 {
	public String name;
	public int age;
	public String toString() {
		return "我是:"+name+",年齡是:"+age;
	}
	public int countContent(String src,String dst) {
		int count=0;
		int index=src.indexOf(dst);
		while(index!=-1) {
			count++;
			index+=dst.length();
			index=src.indexOf(dst,index);
		}
		return count;
	}
public static void main(String[] args) {
	Demo6 demo6=new Demo6();
	demo6.name="張三";
	demo6.age=20;
	System.out.println(demo6.toString());
	String src="朋友啊朋友,你是我最好的好朋友";
	String dst="朋友";
	int count=demo6.countContent(src, dst);
	System.out.println(dst+"出現的次數爲:"+count);
}
}

更多具體方法請查看api文檔java

相關文章
相關標籤/搜索