Java_常用类之String和StringBuffer

常用类_String类


1. String类概述

String类代表字符串,属于Java.lang下的。特殊的引用类型,作为参数传递跟基本类型是一样的(形参的改变不影响实际参数)Java中所有字符串字面值都可看作是此实现类的实例;

语法:String s = “字符串值” ;

  • String s = “Hello”;产生一个对象,保存在池中

  • String s2 = new String(“World”); 产生两个对象,池、堆各一个

2. String类特点

  • 字符串不变:字符串是一个常量,值在创建后不能被更改(内存中产生常量池);
  • 因为不可变,所以可以共享;

3. 构造方法

  • public String():空参构造,初始化一个新创建的String对象,使其空字符序列;
String s1 = new String() ;
System.out.println(s1+"---"+s1.length());
  • public String(char[] value) :将字符数组转换成新的字符串
char[] chs = {'a','b','c','d','e'} ;
String s = new String(chs) ;
System.out.println(s);//"abcde"
System.out.println(s.length());//5
  • String(char[] value, int offset, int count):将字符数组的一部分转换成字符串
char[] chs = {'a','b','c','d','e'} ;
String s = new String(chs, 2, 3) ;//第二个角标开始三个长度转化  ade
System.out.println(s);//"cde"
System.out.println(s.length());//3
  • public String(byte[] bytes) :将字节数转换成字符串
byte[] bytes = {97,98,99,100,101} ; 
String s = new String(bytes) ; //ASCII码表中对应的字符
System.out.println(s);//abcde
System.out.println(s.length());//5
  • public String(byte[] bytes, int offset, int length):将字节数组一部分转换成字符串内容
byte[] bytes = {97,98,99,100,101} ; 
String s = new String(bytes, 1, 2) ;//从下标为1开始转化2个长度
System.out.println(s);//bc
System.out.println(s.length());
  • String(String original) :直接传递一个字符串常量值 String(“hello”)
String s = new String("hello") ; 
System.out.println(s);//hello
System.out.println(s.length());

4. 常用方法

4.1 判断功能

  • public boolean equals (Object anObject): (常用)比较两个字符串内容是否相同,区分大小写;

  • public boolean equalsIgnoreCase (String anotherString):比较两个字符串的内容是否相同,不区分大小写;

  • public boolean isEmpty(): 判断对象是否为空;

  • public boolean contains(String s):判断字符串是否包含在指定字符串中;

  • public boolean startsWith(String prefix) :判断字符串是否以指定的字符串开头(了解)

  • public boolean endsWith(String suffix) : 判断字符串是否以指定的字符串结束(了解)

public static void main(String[] args) {
		String s1 = "helloWorld" ;
		String s2 = "HelloWORLD" ;
    
		//	public boolean equals (Object anObject)
		System.out.println("equals:"+s1.equals(s2));//false
    
		//public boolean equalsIgnoreCase (String anotherString)
		System.out.println("eqalsIgoreCase:"+s1.equalsIgnoreCase(s2));//true
    
		//public boolean isEmpty(): 判断对象是否为空
		System.out.println("isEmpty()"+s1.isEmpty());//false
    
		// public boolean contains(String s):
		System.out.println("contains:"+s1.contains("kaka"));//false
		System.out.println("contains:"+s1.contains("orl"));//true
            
		//public boolean startsWith(String prefix) 
		System.out.println("startsWith:"+s1.startsWith("hel"));//true
    
		//public boolean endsWith(String suffix) :
		System.out.println("endsWith:"+s1.endsWith("ld"));//true
	}

String的数值地址问题_01:

public class StringDemo {
	public static void main(String[] args) {
		String s1 = new String("hello");
		String s2 = new String("hello");
        //s1,s2都new了产生新的不一样的地址,所以地址值不同,但是内容相同
		System.out.println(s1 == s2);//false
		System.out.println(s1.equals(s2));//true
		System.out.println("-------------");
		
		String s3 = new String("hello");
		String s4 = "hello";
        //s3new了产生了一个地址但s4在常量池中。
		System.out.println(s3 == s4);//false
		System.out.println(s3.equals(s4));//true
		System.out.println("-------------");
		
		String s5 = "hello";
		String s6 = "hello";
        //s5和s6都在常量池中,是同一个地址
		System.out.println(s5 == s6);//true
		System.out.println(s5.equals(s6));//true
	}

== 和equals的区别:

  • == :连接的是两个对象,比较的两个对象地址值是否相同

  • 某个对象.equals(传递一个对象):默认比较是地址值但是String类重写了equals方法,所以比较字符串的内容是否相同

String的数值地址问题_02:

public static void main(String[] args) {
		String s1 = "hello";
		String s2 = "world";
		String s3 = "helloworld";
		//变量
		System.out.println(s3 == s1 + s2);//false
		System.out.println(s3.equals(s1 + s2));//true
		
		//常量
		System.out.println(s3 == "hello"+"world");//true  
		System.out.println(s3.equals("hello"+"world"));//true
	}
}

字符串常量:

  • 字符串常量相加,先相加,然后拿结果数据在常量池中是否存在这个值,如果存在,返回地址;如果不存在,在空开间;

字符串变量:

  • 字符串变量相加,先开空间,然后在拼接,形成新的地址;

4.2 获取功能

  • public int length () :返回此字符串的长度(实际长度);

  • public String concat (String str) :将指定的字符串连接到该字符串的末尾。(拼接的功能);

  • public char charAt (int index) :返回指定索引处的 char值;

  • public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引;

  • public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取字符串到字符串结尾;

  • public String substring (int beginIndex, int endIndex) :返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex;

public static void main(String[] args) {
		//定义一个字符串
		String s = "hellojava" ;
		//public int length ()
		System.out.println("length:"+s.length());//9
    
		//public String concat (String str) 
		String s1 = "ee" ;
		String s2 = s.concat(s1) ;
		System.out.println("s2:"+s2);//hellojavaee

		//public char charAt (int index) 
		System.out.println("charAt:"+s.charAt(4)); //o
    
		//public int indexOf (String str)
		System.out.println("indexOf:"+s.indexOf("l"));//2
    
		//public String substring (int beginIndex)
		System.out.println("substring:"+s.substring(5));//java
    
		//public String substring (int beginIndex, int endIndex):包前不包后
		System.out.println("substring:"+s.substring(5, 9));//java
	}

案例:键盘录入一个字符串数据,将这个数据的第一个字母变成大写,后面的数据全部小写;

public static void main(String[] args) {
		//创建键盘录入对象
		Scanner sc = new Scanner(System.in)//录入数据
		System.out.println("输入一个字符串:");
		String line = sc.nextLine() ;
		
		//1)将该字符串数的第一个字符,转换成大写
		//先截取第一个字符
		String s1 = line.substring(0, 1) ;
		String s2 = s1.toUpperCase() ;
		
		//2)将除了第一个字符以外的数据截取,并转成小写
		String s3 = line.substring(1) ;
		String s4 = s3.toLowerCase() ;
		
		//将s2和s4进行拼接
		String result = s2.concat(s4) ;
		System.out.println("result:"+result);
		System.out.println("------------------");
		//方式二
		String str = line.substring(0, 1).toUpperCase().
					concat(line.substring(1).toLowerCase()) ;
		System.out.println(str);
	}

4.3 转换功能

  • String toLowerCase() : 转换小写

  • String toUpperCase() :转换大写

  • public char[] toCharArray():将字符串转换成字符数组

  • public static String valueOf(int i) :将int类型转换成字符串

  • public byte[] getBytes() :使用平台默认编码集(GBK)将字符串转换成字节数组

//转大写	
String s = "hellojava" ;
System.out.println(s.toUpperCase());
//转小写
String s = "HELLOJAVA" ;
System.out.println(s.toUpperCase());
//将字符串转换成字符数组
char[] chs = s.toCharArray();
for(int i = 0;i < chs.length;i++){
	System.out.println(chs[i]);
}
//将int类型转化为字符串
int j = 10000;
System.out.println(String.valueOf(j));
//字符串转化为字符数组
byte[] b = s.getBytes();//使用默认编码集转化为字节数组
for(int i1 = 0;i1<b.length;i1++){
    System.out.println(b[i1]);
}  

4.4 分割功能

public String[] split(String regex) :将字符串按照regex拆分为字符串数组

String str = "hji-hi-sd-bih";
String[] strArray = str.split("-");//遇到“——”进行分割 
for(int k = 0;k < strArray.length;k++){
	System.out.println(strArray[k]);
}

4.5 替换功能

public String replace(char oldChar,char newChar):将新的字符进行替换(newChar–替换oldChar);

public String replace(String oldStr,String newStr):将新的字符串替换掉以前的旧的子串;

public String trim() :去除两端空格

public static void main(String[] args) {
		//定义一个字符串
		String s = "helloworldjava" ;
		
		//将新的字符进行替换
		System.out.println("s:"+s.replace('l', 'k'));//hekkoworkdjava
    
		//将新的字符串替换掉
		System.out.println("s:"+s.replace("owo", "ooo"));//hellooorldjava

		//去除两端空格
		String s1 = "  hello  world " ;
		System.out.println("s1:"+s1+"---");//  hello  world ---
		String s2 = s1.trim() ;
		System.out.println("s2:"+s2+"---");//hello  world---
	}

4.6 按照字典顺序比较

  • public int compareTo(String anotherString):一般常用的比较(区分大小写的)
  • public int compareToIgnoreCase(String str):不考虑大小进行比较
public static void main(String[] args) {
		//	一般常用的比较(区分大小写的)
		String s3 = "hello" ; 
		String s4 = "hello" ;
		String s5 = "abc"  ;
		String s6 = "xyz" ;
   	 //不相同时用ASCII码值进行计算
		System.out.println("compareTo():"+s3.compareTo(s4));//0
		System.out.println("compareTo():"+s3.compareTo(s5));//7
		System.out.println("compareTo():"+s3.compareTo(s6));//-16
	}

案例1:给定一个int类型数组,拼接为字符串

  • 格式:int[] arr = {11,22,33} -----> [11,22,33]
public static void main(String[] args) {
		int [] arr = {11,22,33};
		String result = arrayToString(arr);
		System.out.println("result:"+result);
	}
	private static String arrayToString(int[] arr) {
		//定义一个空字符串  
		String result = "" ;
		result += "[" ;
		
		//遍历int类型的数组
		for(int x = 0 ; x < arr.length ; x ++) {
			//如果x是最大索引处
			if(x==arr.length-1) {
				result += arr[x] ;
				result += "]" ;
			}else {
				result += arr[x] ;
				result += ", " ;
			}
		}
		return result;
	}
}

案例2:键盘录入一个字符串,统计字符串的大写字母字符,小写字母字符,数字字符分别多少个?

思路:

  • 键盘录入字符串;

  • 遍历字符串把每个字符获取出来

  • 通过charAt将每个字符串变为字符

  • 判断范围:

    A~Z:大写字符

    a~z:小写字符

    0~9:数字字符

public static void main(String[] args) {
		int numCount = 0 ;  //数字
		int lowerCount = 0 ;//小写
		int upperCount = 0 ;//大写
		

		Scanner sc = new Scanner(System.in) ;
		System.out.println("请输入一个字符数组:");
		String line = sc.next() ;
		//遍历字符串
		for(int x = 0 ;x < line.length() ; x ++) {
			//将每个字符串转换字符
			char ch = line.charAt(x) ;
			//获取到每一个字符
			if(ch>='A' && ch <='Z') {
				upperCount ++ ;
			}else if(ch >= 'a' && ch <='z') {
				lowerCount ++ ;
			}else if(ch >= '0' && ch<='9') {
				numCount ++ ;
			}
		}
		
		System.out.println("大写字母字符共有:"+upperCount+"个");
		System.out.println("小写字母字符共有:"+lowerCount+"个");
		System.out.println("数字字符共有:"+numCount+"个");
	}
}

常用类_StringBuffer

1. StringBuffer类概述

StringBuffer:线程安全的可变字符序列;

String、StringBuilder和StringBuffer的区别:

  • String:字符串是常量,作为方法形参传递,不会改变实际参数,一旦被赋值不能被更改;

  • StringBuffer;线程安全的可变字符序列,线程安全,执行效率低(字符串缓冲区);

  • StringBuilder:线程不安全的类,单线程程序中使用,不同步,执行效率高;

2. StringBuffer类的构造方法

字符串缓冲区存储的还是字符串,类型是StringBuffer;

public StringBuffer() : 空参构造,开辟默认的缓冲区大小;

public StringBuffer(int capacity):构造一个缓冲区,带有指定初始容量的缓冲区(理论值)

StringBuffer(String s):将一个字符串构造成到字符串缓冲区中

  • 初始容量:等于当前字符串长度+16个初始容量
  • StringBuffer sb = “hello”;//错误类型不匹配
public static void main(String[] args) {
		//创建一个字符串缓冲区对象(空间足够大)
		StringBuffer sb = new StringBuffer() ;
		System.out.println(sb); //StringBuffer重写Object的toString方法,不打印地址值;构造了一个缓存区对象,里面没有内容
		System.out.println(sb.length());//0
		System.out.println(sb.capacity());//16

		//创建一个带字符串内容的缓冲区
		StringBuffer sb2 = new StringBuffer("hellojava");
		System.out.println(sb2);//hellojava
		System.out.println(sb2.length());//9
		System.out.println(sb2.capacity());//25
		
		//指定带具体的容量的缓冲大小(了解)
		StringBuffer sb3 = new StringBuffer(50) ;
		System.out.println(sb3);
		System.out.println(sb3.length());//0
		System.out.println(sb3.capacity());//50

3.常用方法

3.1 添加功能

StringBuffer append(int/boolan/long…String/StringBuffer…)将这些数据添加到指定的缓冲区末尾,返回值是StringBuffer本身;

public StringBuffer insert(int offset,String str):在指定的位置处插入指定str字符串;

public static void main(String[] args) {
		//创建一个缓冲区对象
		StringBuffer sb = new StringBuffer() ; //底层char [] char = new char[16] ;
		System.out.println("sb:"+sb); //空的
    
		sb.append("hello");
		sb.append("A");
		sb.append(true);
		sb.append(12);
		System.out.println("sb:"+sb);//helloAtrue12
		
		StringBuffer sb1 = new StringBuffer();
		sb1.append("hello").append("Java").append(100);
		System.out.println("sb1:"+sb1);//helloJava100
		
		//insert指定字符插入
		sb.insert(3, "kaka") ;
		System.out.println("sb:"+sb);//helkakaloAtrue12
	}

3.2 删除功能

StringBuffer deleteCharAt(int index):删除指定位置处的字符,返回字符串缓冲区本身(重点)

public StringBuffer delete(int start,int end),删除从指定位置到指定位置结束(end-1),返回字符串缓冲区本身

public static void main(String[] args) {
    //创建缓冲区对象
    StringBuffer sb = new StringBuffer() ;
    sb.append("hello").append("Java").append("100") ;
    System.out.println(sb);//helloJava100
    System.out.println("sb:"+sb.deleteCharAt(5));//	helloava100
    //第二个索引开始删除5-1个字符
    System.out.println("sb:"+sb.delete(2, 5));//heava100
}

3.3 反转功能

public StringBuffer reverse():将缓存区中的字符序列—反转

public String toString():将字符串缓冲区对象—转成String

public static void main(String[] args) {
    //键盘录入字符串,将字符串进行反转------>结果String
    Scanner sc = new Scanner(System.in) ;

    //提示并录入数据
    System.out.println("输入一个字符串:");
    String line = sc.next() ;

    StringBuffer sb = new StringBuffer(line) ;
    String result = sb.reverse().toString() ;
    
    StringBuffer sb2 = sb.reverse() ;
    String result = sb2.toString() ;
    System.out.println("result:"+result);
}

3.4 替换功能

public StringBuffer replace(int start,int end,String str):使用指定的字符串替换,从指定位置开始,到指定位置结束(end-1);

public static void main(String[] args) {
    //创建一个缓冲区对象
    StringBuffer sb = new StringBuffer() ;
    //追加内容
    sb.append("hello").append("java").append("EE") ;
    System.out.println("sb:"+sb);//hellojavaEE
    //从第5个位置开始到7个位置结束进行替换
	System.out.println("replace:" + sb.replace(5, 7, "kaka"));//hellokakavaEE
}

3.5 截取功能

public String substring(int start):start开始直到结束

public String substring(int start,int end):end-1处结束进行截取

4.String和StringBuffer的相互转化:

不转化用造成类型不匹配异常

4.1 String---->StringBuffer

public static void main(String[] args) {
    String s = "hello" ;
    //方式1:通过StringBuffer的构造方法 
    StringBuffer sb = new StringBuffer(s) ;
    System.out.println(sb);//hello,类型还是StringBuffer

    //方式2:空参构造+append(...)
    StringBuffer sb2 = new StringBuffer() ;
    sb2.append(s) ;
    System.out.println(sb2);//hello
}

4.2 StringBuffer----->String

public static void main(String[] args) {
   StringBuffer buffer = new StringBuffer("world") ;	
    //方式1:public String(StringBuffer buffer) 构造方法
    String str = new String(buffer) ;
    System.out.println(str);//world String类型
    
    //方式2:public String toString() 利用toString
    String str2 = buffer.toString() ;
    System.out.println(str2);
	}

5.StringBuffer和数组的区别

  • 两者都是容器
    StringBuffer字符串缓冲区,可以存储任意类型的数据,在缓冲区中拼接—>始终是一个字符串内容
    数组只能存储同一种类型的元素

  • 获取缓冲区中字符串长度以及获取数组的长度方式不一样
    StringBuffer是length() 方法

    数组是length属性

  • StringBuffer sb = new StringBuffer()相当于创建一个默认的容量的字符数组作为一个缓冲区

String类型和StringBuffer类型作为方法形参有什么不一样的地方

public static void main(String[] args) {
	String s1 = "hello" ;
	String s2 = "world" ;
	System.out.println("s1:"+s1+",s2:"+s2);//s1:hello,s2:world
	change(s1,s2) ;
	System.out.println("s1:"+s1+",s2:"+s2);//s1:hello,s2:world
	
	//引用类型作为参数传递:改变的只是内容,地址值不变
	StringBuffer sb1 = new StringBuffer("hello") ;
	StringBuffer sb2 = new StringBuffer("world") ;
	System.out.println("sb1:"+sb1+",sb2:"+sb2);//s1:hello,s2:world (StringBuffer类型)
	change(sb1,sb2)  ;
	System.out.println("sb1:"+sb1+",sb2:"+sb2);//sb1:hello,sb2:worldworld
}
	//sb1 sb2:形式参数
	private static void change(StringBuffer sb1, StringBuffer sb2) {
        //(只是内容替换为world,地址还是hello,传上去仍然是hello)
		sb1 = sb2 ;//sb1="world"
		sb2.append(sb1) ; //"world","world"
	}
	private static void change(String s1, String s2) {
		s1 = s2 ;  //s1 = s2 = "world"
		s2 = s1 + s2 ; //s2 = s1("world") +s2("world")
	}
}

  • String:特殊的引用类型,字符串类型,作为参数传递和基本数据类型作为参数传递效果一样,形参的改变,对实际参数没有影响;

  • StringBuffer就是引用类型,形参的改变会直接实际参数(只是内容,不改变实际值)。缓冲区: 存储的内容字符串内容(常量);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Willing卡卡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值