java字符串String介绍

1、实例化String对象 直接赋值: String str="hello"; 使用关键字new: String str=new String("hello");

这里写图片描述

可以看出直接赋值节省了内存空间。

字符串的比较:
package ds;

public class savg {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="hello";
String str1=new String("hello");
System.out.println(str==str1);
		
	}

}

结果是:false ,所以使用双等无法进行比较

“==”比较的是地址,eqrals计较的是内容

所以得使用:System.out.println(str.equals(str1));

二:String字符串的内容不能更改
package ds;

public class savg {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="hello";
String str1=str+"world";
System.out.println(str1);
		
	}

}

结果是:helloworld
这里写图片描述
三:String字符串的常用方法

1:字符串长度length()方法

String str = “wolaile”;
System.out.println(str.length());
2:字符串转换为数组:通过toCharArray();

package ds;
public class dabd {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	String str = "wolaile";
	char ga[]=str.toCharArray();
	System.out.println(ga);
	
}

}



**3:从字符串中取出指定位置的字符:charAt();**

package ds;

public class dabd {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	String str = "wolaile";
	//char ga[]=str.toCharArray();
	//System.out.println(ga);
	System.out.println(str.charAt(3));
}

}
//结果是a

**4:字符串与Byte数组的转换:getBytes();**

package ds;

public class test45 {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	String str = "wolaile";
	byte jy[]=str.getBytes();
	System.out.println(jy);
	
	System.out.println(new String(jy));
	
	
}

}

**5:显示字符对应的下角标:indexOf();**

package ds;

public class eyh {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	String str = "wolaile@";
	System.out.println(str.indexOf("@"));
	
	
}

}

**6:去掉字符串的前后空格:trim()**

package ds;

public class eyh {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	String str = "  wolaile@";
	//System.out.println(str.indexOf("@"));
	
	System.out.println(str.trim());
}

}

![这里写图片描述](https://img-blog.csdn.net/20180331105729295?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d6MTI0NTE5MTE0NQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)





(https://blog.csdn.net/qq_37267015/article/details/59627656)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值