String字符串

String字符串的运算&String类的常用 方法

let the code talk:

package april;

public class StringTest {
	
	public static void main(String args[]) {
    	
		//1.字符串赋值
		
		String str1 = "abcde12345";   			//String字符串不能用单引号('')表示
		String str2 = "abcde";
		String str3 = "12345";
		String output;
		
		//2.字符串运算(字符串不能进行'-'运算)
		
		output = str2 + str3;					//output为“abcde12345”
		System.out.println("output = "+output);
		output = str2 + "12345"; 				//output为“abcde12345”
		System.out.println("output = "+output);
		str2 += str3;							//str2为“abcde12345”
		System.out.println("str2 = "+str2);
				
		//3.String类的常用方法
		
		//(1)length():返回字符串长度
		System.out.println("str1的长度为:"+str1.length());
		
		//(2)equals(Object anObject):将给定字符串与当前字符串想对比,如果相同返回true,否则返回false
		System.out.println("str1与output是否相同:"+str1.equals(output));
		
		//(3)subString(int beginIndex):返回字符串从beginIndex开始的字符串
		//字符串的首位也是从0开始
		System.out.println("str1串从第(2+1)个字符开始的字符串:"+str1.substring(2));
		
		//(4)subString(int beginIndex,int endIndex):返回字符串从beginIndex开始到endIndex的字符串,不包括endIndex
		System.out.println("str1返回字符串从第(2+1)个字符开始到第(4+1)个字符的字符串:"+str1.substring(2,4));
		
		//(5)charAt(int index):返回字符串中指定位置的字符
		System.out.println("str1中第(2+1)个字符:"+str1.charAt(2));
		
		//(6)indexOf(String str):返回str在字符串中首次出现的位置
		System.out.println("str1中'c'在字符串中首次出现的位置:"+str1.indexOf('c'));
		
		//(7)replace(char oldChar,char newChar):以newChar替换字符串中所有的oldChar
		System.out.println("将str1中'e'替换为'0':"+str1.replace('e', '0'));
		
		//(8)trim():去掉字符串的首尾空格
		String str4 = "   aaa   ";
		System.out.println("str4 ="+str4);
		str4 = str4.trim();
		System.out.println("str4去掉首位空格符:"+ str4);
		
		
    }

}

running ...

result:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值