您的位置:首页 > 编程语言 > Java开发

java字符串

2015-06-18 10:15 399 查看
1.连接字符串:使用+号
public static void main(String[] args) {
		String s1="abc";
		String s2="def";
		System.out.println(s1+s2);
	}


输出为abcdef

2.获取字符串长度

public static void main(String[] args) {
		String s1="abc";
		int a=s1.length();
		System.out.println(a);
	}


输出为3

3.查找字符串

public static void main(String[] args) {
		String s1="abcb";
		int a=s1.indexOf("b");
		int b=s1.lastIndexOf("b");
		char c=s1.charAt(0);
		System.out.println(a+" "+b+" "+c);
	}


输出为1 3 a如果没有检索到返回值为-1

4.字符串操作

subString()截取字符串

trim()去除空格//只是去除前面空格和尾部空格,中间不变

replace()字符串替换

public static void main(String[] args) {
		String s1=" ab cb ";
		String t1=s1.substring(1, 3);
		String t2=s1.trim();
		String t3=s1.replace("b", "B");
		System.out.println(t1);
		System.out.println(t2);
		System.out.println(t3);
	}


输出为
ab
ab cb
 aB cB


5.判断字符串是否相等

public static void main(String[] args) {
		String s1=new String("abc");
		String s2=new String("abc");
		String s3="abc";
		String s4="abc";
		System.out.println(s1.equals(s2));
		System.out.println(s1==s2);
		System.out.println(s1==s3);
		System.out.println(s3==s4);
	}


输出为
true
false
false
true


s1和s2都new出了一个新对象,他们在内存中的地址是不同的,s3和s4没有new,它们都指向内存中存储变量的一块地址

6.字符串分割split()返回一个字符串数组
public static void main(String[] args) {
		String s="ab,cd,ef";
		String[] t1=s.split(",",2);
		for(int i=0;i<t1.length;i++){
			System.out.println(t1[i]);
		}
	}


输出为
ab
cd,ef
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: