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文档

转载于:https://my.oschina.net/u/3740271/blog/1941017

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值