Java的字符串

Java中的字符串是由双引号括起来的多个字符。Java中的字符采用Unicode编码。

单个字符如果用双引号括起来,由其表示的是字符串,而不是字符。

Java SE提供了三个字符串类:String、StringBuffer、StringBuilder。String是不可变字符串,StringBuffer和StringBuilder是可变字符串。

不可变字符串和可变字符串的区别在于当字符串进行拼接等修改操作时,不可变字符串会创建新的字符串对象,而可变字符串不会创建对象。

Java中不可变字符串类是String,属于java.lang包,它也是java非常重要的类。

String():使用空字符串创建并初始化一个新的String对象。

String(String original):使用另外一个字符串创建并初始化一个新的String对象。

String(StringBuffer buffer):使用可变字符串对象(StringBuffer)创建并初始化一个新的String对象。

String(StringBuffer builder):使用可变字符串对象(StringBuffer)创建并初始化一个新的String对象。

String(byte[] bytes):使用平台的默认字符集解码指定的byte数组,通过byte数组创建并初始化一个新的String对象。

String(char[] value):通过字符数组创建并初始化一个新的String对象。

String(char[] value, int offset, int count):通过字符数组的子数组创建并初始化一个新的String对象;offset参数是子数组第一个字符的索引,count参数指定子数组的长度。

创建字符串对象示例代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1=new String();
		String s2=new String("Hello World");
		String s3=new String("\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064");
		System.out.println("s2 = "+s2);
		System.out.println("s3 = "+s3);
		
		char chars[]= {'a','b','c','d','e'};
		String s4=new String(chars);
		String s5=new String(chars,1,4);
		System.out.println("s4 = "+s4);
		System.out.println("s5 = "+s5);
		
		byte bytes[]= {97,98,99};
		String s6=new String(bytes);
		System.out.println("s6 = "+s6);
		System.out.println("s6字符串长度 = "+s6.length());
	}

}

输出结果:

s2 = Hello World
s3 = Hello World
s4 = abcde
s5 = bcde
s6 = abc
s6字符串长度 = 3

字符串池:(代码错误,未掌握)

Java中的不可变字符串String常量采用字符串池(String Pool)管理技术,字符串池是一种字符串驻留技术 。

代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s7=new String("Hello");
		String s8=new String("Hello");
		
		String s9="Hello";
		String s10="Hello";
		
		System.out.printf("s7 == s8 : %b%n, s7==s8");
		System.out.printf("s9 == s10: %b%n, s9==s10");
		System.out.printf("s7 == s9 : %b%n, s7==s9");
		System.out.printf("s8 == s9 : %b%n, s8==s9");
	}

}

运行结果:

s7 == s8 : Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%b'
	at java.util.Formatter.format(Unknown Source)
	at java.io.PrintStream.format(Unknown Source)
	at java.io.PrintStream.printf(Unknown Source)
	at helloworld.helloworld.main(helloworld.java:13)

字符串拼接:

字符串拼接示例如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1="Hello";
		//使用+运算符连接
		String s2=s1+" ";
		String s3=s2+"World";
		System.out.println(s3);
		
		String s4="Hello";
		//使用+运算符连接,支持+=赋值运算符
		s4+=" ";
		s4+="World";
		System.out.println(s4);
		
		String s5="Hello";
		//使用concat方法连接
		s5=s5.concat(" ").concat("World");
		System.out.println(s5);
		
		int age=18;
		String s6="Her ages is "+ age +" age old.";
		System.out.println(s6);
		
		char score='A';
		String s7="Her English score is "+score+".";
		System.out.println(s7);
		
		java.util.Date now=new java.util.Date();
		String s8="Today is "+now +".";
		System.out.println(s8);
	}

}

输出结果:

Hello World
Hello World
Hello World
Her ages is 18 age old.
Her English score is A.
Today is Fri Jan 07 13:32:37 CST 2022.

字符串查找:

在String类中提供了indexOf和lastIndexOf方法用于查找字符或字符串,返回值是查找的字符或字符串所在的位置,-1表示没有找到。

int indexOf(int ch):从前往后搜索字符ch,返回第一次找到字符ch所在处的索引。
int indexOf(int ch, int fromIndex):从指定的索引开始从前往后搜索字符ch,返回第一次找到字符ch所在处的索引。
int indexOf(String str):从前往后搜索字符串str,返回第一次找到字符串str所在处的索引。
int indexOf(String str, int fromIndex):从指定的索引开始从前往后搜索字符串str,返回第一次找到字符串str所在处的索引。
int lastIndexOf(int ch):从后往前搜索字符ch,返回第一次找到字符ch所在处的索引。
int lastIndexOf(int ch, int fromIndex):从指定的索引开始从后往前搜索字符ch,返回第一次找到字符ch所在处的索引。
int lastIndexOf(String str):从后往前搜索字符串str,返回第一次找到字符串str所在处的索引。
int lastIndexOf(String str, int fromIndex):从指定的索引开始从后往前搜索字符串str,返回第一次找到字符串str所在处的索引。

字符串查找示例代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String sourceStr ="There is a string accessing example.";
		//获得字符串长度
		int len= sourceStr.length();
		//获得索引位置16的字符
		char ch= sourceStr.charAt(16);
		
		//查找字符和子字符串
		int firstChar1= sourceStr.indexOf('r');
		int lastChar1= sourceStr.lastIndexOf('r');
		int firstStr1= sourceStr.indexOf("ing");
		int lastStr1= sourceStr.lastIndexOf("ing");
		int firstChar2= sourceStr.indexOf('e', 15);
		int lastChar2= sourceStr.lastIndexOf('e', 15);
		int firstStr2=	sourceStr.indexOf("ing", 5);
		int lastStr2= sourceStr. lastIndexOf ("ing", 5);
		System.out.println("原始字符串:"+ sourceStr);
		System.out.println("字符串长度:"+len);
		System.out.println("索引16的字符:"+ch);
		System.out.println("从前往后搜索r字符,第一次找到它所在索引:" +firstChar1);
		System.out.println("从后往前搜索r字符,第一次找到它所在索引:" +lastChar1);
		System.out.println("从前往后搜索ing字符串,第一次找到它所在索引:" +firstStr1);
		System.out.println("从后往前搜索ing字符串,第一次找到它所在索引:" +lastStr1);
		System.out.println("从索引为15位置开始,从前往后搜索e字符,第一次找到它所在索引:"+firstChar2);
		System.out.println("从索引为15位置开始,从后往前搜索e字符,第一次找到它所在索引:"+lastChar2);
		System.out.println("从索引为5位置开始,从前往后搜索1ng字符串,第一次找到它所在索引:"+firstStr2);
		System.out.println("从索引为5位置开始,从后往前搜索ing字符串,第一次找到它所在索引:"+lastStr2);

	}

}

输出结果如下:

原始字符串:There is a string accessing example.
字符串长度:36
索引16的字符:g
从前往后搜索r字符,第一次找到它所在索引:3
从后往前搜索r字符,第一次找到它所在索引:13
从前往后搜索ing字符串,第一次找到它所在索引:14
从后往前搜索ing字符串,第一次找到它所在索引:24
从索引为15位置开始,从前往后搜索e字符,第一次找到它所在索引:21
从索引为15位置开始,从后往前搜索e字符,第一次找到它所在索引:4
从索引为5位置开始,从前往后搜索1ng字符串,第一次找到它所在索引:14
从索引为5位置开始,从后往前搜索ing字符串,第一次找到它所在索引:-1

字符串比较:

1、比较相等

boolean equals(Object anObject):比较两个字符串中内容是否相等。

boolean equalsIgnoreCase(String anotherString):类似equals方法,只是忽略大小写。

2、比较大小

int compareTo(String anotherString):按字典顺序比较两个字符串。如果参数字符串等于此字符串,则返回值0;如果此字符串小于参数字符串,则返回一个小于0的值;如果此字符串大于参数字符串,则返回一个大于0的值。

int compareToIgnoreCase(String str):类似compareTo,只是忽略大小写。

3、比较前缀和后缀

boolean endsWith(String suffix):测试此字符串是否以指定的后缀结束。

boolean startsWith(String prefix):测试些字符串是否以指定的前缀开始。

字符串比较示例代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1=new String("Hello");
		String s2=new String("Hello");
		//比较字符串是否是相同的引用
		System.out.println("s1==s2:"+(s1==s2));
		//比较字符串内容是否相等
		System.out.println("s1.equals(s2):"+(s1.equals(s2)));
		
		String s3="HELLO";
		//忽略大小写比较字符串内容是否相等
		System.out.println("s1.equalsIgnoreCase(s3):"+(s1.equalsIgnoreCase(s3)));
		
		//比较大小
		String s4="java";
		String s5="Swift";
		//比较字符串大小 s4>s5
		System.out.println("s4.compareTo(s5):"+(s4.compareTo(s5)));
		//忽略大小写比较字符串大小 s4<s5
		System.out.println("s4.compareToIgnoreCase(s5):"+(s4.compareToIgnoreCase(s5)));
		//判断文件夹中文件名
		String[] docFolder= {"java.docx","JavaBean.docx","Objecitive-C.xlsx","Swift.docx"};
		int wordDocCount=0;
		//查找文件夹中Word文档个数
		for(String doc:docFolder) {
			//去掉前后空格
			doc=doc.trim();
			//比较后缀是否有.docx字符串
			if(doc.endsWith(".docx")) {
				wordDocCount++;
			}
		}
		System.out.println("文件夹中word文档个数是: "+wordDocCount);
		
		int javaDocCount=0;
		//查找文件夹中Java相关文档个数
		for(String doc: docFolder) {
			//去掉前后空格
			doc=doc.trim();
			//全部字符转成小写
			doc=doc.toLowerCase();
			//比较前缀是否有java字符串
			if(doc.startsWith("java")) {
				javaDocCount++;
			}
		}
		System.out.println("文件夹中Java相关文档个数是: "+javaDocCount);
	}

}

输出结果:

s1==s2:false
s1.equals(s2):true
s1.equalsIgnoreCase(s3):true
s4.compareTo(s5):23
s4.compareToIgnoreCase(s5):-9
文件夹中word文档个数是: 3
文件夹中Java相关文档个数是: 2

字符串截取:

String substring(int beginIndex):从指定索引beginIndex开始截取一直到字符串结束的子字符串。

String substring(int beginIndex, int endIndex):从指定索引beginIndex开始截取直到索引endIndex-1处的字符,注意包括索引为beginIndex处的字符,但不包括索引为endIndex处的字符。

字符串截取方法示例代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String sourceStr="There is a string accessing example.";
		//截取example.子字符串
		String subStr1=sourceStr.substring(28);
		//截取string子字符串
		String subStr2=sourceStr.substring(11,17);
		System.out.printf("subStr1= %s%n", subStr1);
		System.out.printf("subStr2=%s%n", subStr2);
		//使用split方法分隔字符串
		System.out.println("-----使用split方法-----");
		String[] array= sourceStr.split(" ");
		for(String str:array) {
			System.out.println(str);
		}
	}

}

输出结果:

subStr1= example.
subStr2=string
-----使用split方法-----
There
is
a
string
accessing
example.

可变字符串:

Java提供了两个可变字符串类StringBuffer和StringBuilder,中文翻译为“字符串缓冲区”。

StringBuffer和StringBuilder:

StringBuffer是线程安全的,它的方法是支持线程同步,线程同步会操作串行顺序执行,在单纯程环境下会影响效率。StringBuilder是StringBuffer单线程版本,Java5之后发布的,它不是线程安全的,但它的执行效率很高。

StringBuilder():创建字符串内容是空的StringBuilder对象,初始容量默认为16个字符。

StringBuilder(CharSequence seq):指定CharSequence字符串创建StringBuilder对象。CharSequence接口类型,它的实现类有String、StringBuffer和StringBuilder等,所以参数seq可以是String、StringBuffer和StringBuilder等类型。

StringBuilder(int capacity):创建字符串内容是空的StringBuilder对象,初始容量由参数capacity指定。

StringBuilder(String str):指定String字符串创建StringBuilder对象。

上述构造方法同样适合于StringBuffer类。

字符串长度和字符串缓冲区容量示例代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//字符串长度length和字符串缓冲区容量capacity
		StringBuilder sbuilder1=new StringBuilder();
		System.out.println("包含的字符串长度:"+sbuilder1.length());
		System.out.println("字符串缓冲区容量:"+sbuilder1.capacity());
		
		StringBuilder sbuilder2= new StringBuilder("Hello");
		System.out.println("包含的字符串长度:"+sbuilder2.length());
		System.out.println("字符串缓冲区容量:"+sbuilder2.capacity());
		
		//字符串缓冲区初始容量是16,超过之后会扩容
		StringBuilder sbuilder3=new StringBuilder();
		for(int i=0;i<17;i++) {
			sbuilder3.append(8);
		}
		System.out.println("包含的字符串长度:"+sbuilder3.length());
		System.out.println("字符串缓冲区容量:"+sbuilder3.capacity());
	}

}

输出结果:

包含的字符串长度:0
字符串缓冲区容量:16
包含的字符串长度:5
字符串缓冲区容量:21
包含的字符串长度:17
字符串缓冲区容量:34

字符串追加:

代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//字符串长度length和字符串缓冲区容量capacity
		StringBuilder sbuilder1=new StringBuilder("Hello");
		sbuilder1.append(" ").append("World");
		sbuilder1.append('.');
		System.out.println(sbuilder1);
		
		StringBuilder sbuilder2=new StringBuilder();
		Object obj=null;
		//添加布尔值、转义符和空对象
		sbuilder2.append(false).append('\t').append(obj);
		System.out.println(sbuilder2);
		
		//添加数值
		StringBuilder sbuilder3=new StringBuilder();
		for(int i=0; i<10; i++) {
			sbuilder3.append(i);
		}
		System.out.println(sbuilder3);
	}

}

输出结果:

Hello World.
false	null
0123456789

字符串插入、删除和替换

StringBuilder insert(int offset, String str):在字符串缓冲区中索引为offset的字符位置之前插入str,insert有很多重载方法,可以插入任何类型数据

StringBuffer delete(int start, int end):在字符串缓冲区中删除子字符串,要删除的子字符串从指定索引start开始直到索引end-1处的字符。start和end两个参数与substring(int beginIndex, int endIndex)方法中的两个参数含义一样。

StringBuffer replace(int start, int end, String str):在字符串缓冲区中用str替换子字符串,子字符串从指定索引start开始直到索引end-1处的字符。start和end同delete(int start, int end)方法。

示例代码如下:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//原始不可变字符串
		String str1="Java C";
		//从不可变的字符串创建可变字符串对象
		StringBuilder mstr=new StringBuilder(str1);
		
		//插入字符串
		mstr.insert(4," C++");
		System.out.println(mstr);
		
		//具有追加效果的插入字符串
		mstr.insert(mstr.length(), " Objective-C");
		System.out.println(mstr);
		
		//追加字符串
		mstr.append(" and Swift");
		System.out.println(mstr);
		
		//删除字符串
		mstr.delete(11, 23);
		System.out.println(mstr);
	}

}

输出结果:

Java C++ C
Java C++ C Objective-C
Java C++ C Objective-C and Swift
Java C++ C and Swift

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值