Presentation is loading. Please wait.

Presentation is loading. Please wait.

第6章 字符串处理.

Similar presentations


Presentation on theme: "第6章 字符串处理."— Presentation transcript:

1 第6章 字符串处理

2 字符串是字符的序列,它是组织字符的基本的数据结构。Java将字符串当作对象来处理,它提供了一系列的方法对整个字符串进行操作,使得字符串的处理更加容易和规范。在Java中,提供了各种处理字符串的方法。
Java语言中的包java.lang中封装了final类String和StringBuffer,其中类String对象是字符串常量,建立后不能改变。而类StringBuffer对象类似于一个字符缓冲区,建立后可以修改。

3 6.1 类String字符串 6.1.1 类String字符串的定义
String类是字符串常量类,String对象建立后不能修改。以前使用的每个字符串常量(用双引号括起来的一串字符)实际上都是String对象,如字符串“Java”在编译后即成为String对象。因此,可以用字符串常量直接初始化一个String对象。例如: String s = "Hello World. "; 由于每个字符串常量对应一个String类的对象,所以对一个字符串常量可以直接调用类String中提供的方法。

4 将返回字符串的长度12,字符串的长度即字符串中字符的个数。
例如: int len = "Hello World!".length(); 将返回字符串的长度12,字符串的长度即字符串中字符的个数。 通过类String提供的构造方法,可以生成一个空字符串(不包含任何字符的字符串),也可以由字符数组或字节数组来生成一个字符串对象。缺省的构造方法不需要任何参数,它生成一个空字符串。例如: String s = new String(); 其他创建String对象的构造方法有: String(String value)用已知串value创建一个字符串对象。 String(char chars[])用字符数组chars创建一个字符串对象。

5 String(char chars[],int startIndex,int numChars)用字符数组chars的startIndex位置开始的numChats个字符,创建一个字符串对象。
String(byte ascii[],int hiByte)用字节数组ascii创建一个字符串对象,Unicode字符的高位字节为hiByte,通常应该为0。 String(byte ascii[],int hiByte,int startIndex,int numChars)用字节数组ascii创建一个字符串对象。其参数的意义同上。 由于在Internet上通常使用的字符都为8位的ASCII码,Java提供了从字节数组来初始化字符串的方法,并且用hiByte来指定每个字符的高位字节,对ASCII码来说,hiByte应为0,对于其他非拉丁字符集,hiByte的值应该非0。

6 【例6.1】类String构造方法的使用。 public class StringConstructors{
public static void main(String args[]){ String s,s1,s2,s3,s4,s5,s6,s7; byte byteArray[] = {(byte)'J',(byte)'a',(byte)'v',(byte)'a'}; Char charArray[] = {'程','序','设','计'}; StringBuffer sb = new StringBuffer("欢迎");; s = new String("Hello!"); s1 = new String(); s2 = new String(s); s3 = new String(sb); s4 = new String(charArray,2,2); s5 = new String(byteArray,0); s6 = new String(charArray); s7 = new String(byteArray,0,0,1);

7 程序运行结果为: System.out.println("s = "+ s );
} 程序运行结果为: s = Hello! s1 = s2 = Hello! s3 = 欢迎 s4 = 设计 s5 = Java s6 = 程序设计 s7 = J

8 6.1.2 类String 的常用方法 类String中提供的访问String字符串的方法很多,大体上可分为类转换、子字符串、比较、修改等几类。 1.类String字符串的比较 类String中提供了一些方法,用来进行字符串的比较。 (1)boolean equals(Object anObject)和 equalsIgnoreCase(String anotherString) 方法equals()和equalsIgnoreCase()用来比较两个字符串的值是否相等,不同的是后者忽略字母的大小写。例如: System.out.println("abc".equals("abc")); System.out.println("abc".equalsIgnoreCase("ABC"));

9 (2)int compareTo(String anotherString)
注意:它们与运算符“==”实现的比较是不同的。运算符“==”比较两个字符串对象是否引用同一个实例对象,而equals()和equalsIgnoreCase()则比较两个字符串中对应的每个字符是否相同。例如: String s = new String("abc“); String s1= new String(“abc“); // s,s1是两个不同的对象 System.out.println( s == s1 ); // 输出为 false System.out.println("abc"=="abc"); // 输出为 true (2)int compareTo(String anotherString) 为了比较两个字符串的大小,类String中实现了方法compareTo(),通过返回的整数值指明当前字符串与参数字符串的大小关系。若调用的串对象比参数大,返回正整数。反之,返回负整数。相等则返回0。

10 若比较的两个字符串各个位置的字符都相同,仅长度不同,则方法的返回值为:
若比较的两个字符串有不同的字符,则从左边数起的第一个不同字符的大小即两个字符串的大小,字符的大小建立在Unicode字符集基础上。方法的返回值为: this.charAt(k)-anotherString.charAt(k) 例如: System.out.println("this".compareTo("that")); 若比较的两个字符串各个位置的字符都相同,仅长度不同,则方法的返回值为: this.length()-anotherString.length() System.out.println("abc".compareTo("abcd") ); //–1 方法int compareToIgnoreCase(String str)是与上述方法功能相同的方法,但忽略字母大小写。

11 (3)boolean startWith(String prefix)和 boolean endWith(String suffix)
两个方法均有重载: boolean startWith(String prefix,int offset) boolean endWith(String suffix,int offset) 方法startWith()和endWith()用来比较当前字符串的起始字符(或子字符串)prefix和终止字符(或子字符串)suffix是否和调用的字符(或字符串)相同,重载的方法中同时还可以指定比较的开始位置offset。 (4)boolean regionMatches(int toffset,String other,int ooffset,int len) 该方法有重载: boolean regionMatches(boolean ignoreCase, int toffset,String other,int ooffset,int len);

12 regionMatches方法的功能是比较两个字符串中指定区域的子字符串是否相同。
其中,toffset和ooffset分别指明当前字符串和参数字符串中所要比较的子字符串的起始位置,len指明比较的长度,而ignoreCase指明比较时是否区分大小写。无此参数,比较是区分大小写的。 2.类String子字符串和定位 (1)char charAt(int index) 该方法的功能是返回字符串index处的字符,index的值从0到串长度减1。例如: System.out.println("China".charAt(1)); // 输出为h (2)int indexOf(int ch)和lastIndexOf(int ch) 方法indexOf()有重载: indexOf(int ch,int fromIndex) int indexOf(String str)

13 以上方法的功能是返回字符串对象中指定的字符和子串首次出现的位置,从串对象开始处或从fromIndex处开始查找。若未找到则返回-1。
int indexOf(String str,int fromIndex) 以上方法的功能是返回字符串对象中指定的字符和子串首次出现的位置,从串对象开始处或从fromIndex处开始查找。若未找到则返回-1。 方法lastIndexOf()也有重载: int lastIndexOf(int ch,int fromIndex) Int lastIndexOf(String str) int lastIndexOf(String str,int fromIndex) 这几个方法与相应的indexOf方法相比,不同之处是从串对象的右端开始查找。 【例6.2】lastIndexOf的使用。 class LastNumber { public static void main(String args[]) { String s1 = "67.89,55.87,-56.45,11.22,78.9";

14 int i1 = s1.lastIndexOf(',');
String s2 = s1.substring(i1 + 1); System.out.println(s2); } 程序运行结果为: 78.9 (3)String substring(int beginindex)和substring(int beginindex,int endindex) 方法的功能是返回子字符串。前者返回从位置beginindex开始处到串尾的子字符串;后者是返回从beginindex开始到endindex - 1为止的子字符串,子串长度为endindex - beginindex。

15 【例6.3】类String方法indexOf和substring的使用。
class DollarAmount { public static void main(String args[]) { String s1 = "这块显示卡的售价为$45.60"; int i1 = s1.indexOf('$'); String s2 = s1.substring(i1); System.out.println(s2); } 程序运行结果为: $45.60 【例6.4】显示一周星期日至星期六的名称。 class WeekName{ public static void main(String args[]){

16 程序运行结果为: String xq = "日一二三四五六",s; int i; for(i=0;i<7;i++){
s=xq.substring(i,i+1); System.out.print(" 星期"+s); } System.out.println(); 程序运行结果为: 星期日 星期一 星期二 星期三 星期四 星期五 星期六

17 这里,修改的含义是将修改后的字符串对象赋给新的对象或直接输出。
3.类String字符串对象的修改 这里,修改的含义是将修改后的字符串对象赋给新的对象或直接输出。 (1)String toLowerCase()和String toUpperCase() 方法toLowerCase()和toUpperCase()的功能是分别将字符串中的字母转换为小写和大写。例如: System.out.println("abcde".toUpperCase()); System.out.println("ABCDE".toLowerCase()); (2)replace(char oldChar,char newChar) 该方法的功能是将字符串中oldChar字符用newChar字符替换。例如: System.out.println("41177".replace('7','8'));//输出为 41188

18 该方法的功能是截去字符串两端的空白字符(whitespace,不大于‘\u0020’的字符)。例如:
(3)String trim() 该方法的功能是截去字符串两端的空白字符(whitespace,不大于‘\u0020’的字符)。例如: String s = " Java "; String s1 = "他10岁。 "; System.out.println(s.trim()+s1); // 输出为:Java他10岁。 // Java前后的空格字符被截去

19 (1)static String valueOf(Object obj)
static String valueOf(char data[]) static String valueOf(char data[],int offset,int count) static String valueOf(boolean b) static String valueOf(char c) static String valueOf(int i) static String valueOf(long l)

20 例如: 注:其他类也提供了方法valueOf()把一个字符串转换为相应的类对象。例如:
static String valueOf(int i) static String valueOf(long l) static String valueOf(float f) static String valueOf(double d) 例如: System.out.println(String.valueOf(Math.PI)); 注:其他类也提供了方法valueOf()把一个字符串转换为相应的类对象。例如: String piStr = " "; Float pi = Float.valueOf(piStr); //String对象转换为Float对象

21 方法static String toString(int i,int radix)用来将整数i转换为radix进制的数字字符串。例如:
java.lang.Object中提供了方法toString()把对象转换为字符串,这一方法通常被重写以适合子类的需要。下面是一个类Integer使用toString()方法的例子。 方法static String toString(int i,int radix)用来将整数i转换为radix进制的数字字符串。例如: String s = Integer.toString(123,8); // 将十进制的123转换为八进制数据 System.out.println(s); // 输出为 173

22 在实际应用中,也经常需要将字符串转换为其他类型的数据。例如:
String s = "125"; Integer obj = Integer.valueOf(s); int i = obj.intValue(); // 上两行也可合写为: // int i = Integer.valueOf(s).intValue();

23 方法length()的功能为返回类String字符串对象的长度。 【例6.5】求几个给定字符串的平均长度。
(1)int length() 方法length()的功能为返回类String字符串对象的长度。 【例6.5】求几个给定字符串的平均长度。 class StringAverage { public static void main(String args[]) { String array[] = new String[3]; array[0] = "Short string"; array[1] = "This is a complete sentence!"; array[2] = "This is the longest " + "element in the array"; int total = array[0].length(); total += array[1].length(); total += array[2].length();

24 (2)String concat(String str)
System.out.println("平均字符串长度为: " + total/3); } 程序运行结果如下: 平均字符串长度为: 26 (2)String concat(String str) 方法concat()的功能是将str连接到调用串对象的后面,即进行字符串的连接操作。例如: System.out.println("41177".concat("abc")); //41177abc 在Java语言中,重载的运算符“+”也可用来实现字符串的连接或字符串与其他类对象的连接。例如: String s = "Java" + "程序设计"; // s = "Java程序设计" int age = 20; String s1 = "他" + age + "岁。";//s1= "他20岁。"

25 (3)String [ ]split(String str)
class SplitDemo{ public static void main(String args[]){ String s="34,55,78,12,90,81,63,84"; // 逗号分隔的数字字符串 String sa[]=s.split(","); // 给定逗号分隔符分解串后存入数组sa int ia[] = new int [sa.length],sum = 0;

26 程序运行结果如下: for(int i=0;i<sa.length;i++){
ia[i]=Integer.parseInt(sa[i]); sum += ia[i]; } System.out.println("Sum = " + sum); 程序运行结果如下: Sum = 497

27 6.2 类StringBuffer字符串 6.2.1 类StringBuffer字符串的定义
类StringBuffer的对象是一种可以改变(如增长、修改)的字符串对象,使用起来比String类更加方便。在Java语言中支持字符串的加运算,实际上就是使用了StringBuffer类。 类StringBuffer提供了下面几种构造方法对一个可变的字符串对象进行初始化。 StringBuffer()建立空的字符串对象。 StringBuffer(int len)建立长度为len的字符串对象。 StringBuffer(String s)建立一个初值为String类对象s的字符串对象。

28 例如: StringBuffer sb1 = new StringBuffer(); StringBuffer sb2 = new StringBuffer(30); StringBuffer sb3 = new StringBuffer("StringBuffer"); 若不给任何参数,则系统为字符串分配16个字符大小的缓冲区,这是缺省的构造方法。参数len则指明字符串缓冲区的初始长度。参数s给出字符串的初始值,同时系统还要再为该串分配16个字符大小的空间。 这里有两个概念:长度length和容量capacity,前者是类StringBuffer对象中包含字符的数目,而后者是缓冲区空间的大小。例如:对上述初始化的sb3,它的length为12("StringBuffer"的长度),但它的capacity为28。

29 1.设置/获取类StringBuffer字符串对象长度和容量
(1)void ensureCapacity(int minimumCapacity) 本方法的功能是设定字符串缓冲区的大小。保证缓冲区的容量至少为指定的值minimumCapacity 。若当前缓冲区容量小于参数值,则分配新的较大的缓冲区。新容量取以下两者中的大者: 参数minimumCapacity 的值。 老容量的两倍加2。

30 (2)void setLength(int newLength)
例如: StringBuffer sb = new StringBuffer("china"); sb.ensureCapacity(30); System.out.println(sb.capacity()); // 输出为44 (老容量的两倍加2) (2)void setLength(int newLength) 本方法的功能是指明字符串的长度,这时字符串缓冲区中指定长度以后的字符值均为零。例如: sb.setLength(3); // 输出为chi (3)int length() 本方法的功能是获取字符串对象的长度。 (4)int capacity() 本方法的功能是获取缓冲区的大小。

31 【例6.7】StringBuffer字符串长度Length和容量Capacity意义的区别。
class StringBufferDemo { public static void main(String args[]) { StringBuffer sb1 = new StringBuffer(); StringBuffer sb2 = new StringBuffer(30); StringBuffer sb3 = new StringBuffer("abcde"); System.out.println("sb1.capacity = " + sb1.capacity()); System.out.println("sb1.length = " + sb1.length()); System.out.println("sb2.capacity = " + sb2.capacity()); System.out.println("sb2.length = " + sb2.length()); System.out.println("sb3.capacity = " + sb3.capacity()); System.out.println("sb3.length = " + sb3.length()); }

32 2.修改类StringBuffer字符串对象 修改类StringBuffer对象的常用方法有append、insert、delete等。
程序运行结果为: sb1.capacity = 16 sb1.length = 0 sb2.capacity = 30 sb2.length = 0 sb3.capacity = 21 sb3.length = 5 2.修改类StringBuffer字符串对象 修改类StringBuffer对象的常用方法有append、insert、delete等。 (1)StringBuffer append(Object obj) 方法append()用于在串缓冲区的字符串末尾添加各种类型的数据。重载的方法如下: StringBuffer append(boolean b) StringBuffer append(int i) StringBuffer append(long l) StringBuffer append(float f) StringBuffer append(double d)

33 【例6.8】StringBuffer字符串连接操作。 class StringBufferAppend {
public static void main(String args[]) { tringBuffer sb = new StringBuffer("abcde"); sb.append("fgh"); sb.append("ijklmnop"); System.out.println(sb); System.out.println("sb.capacity = " + sb.capacity()); System.out.println("sb.length = " + sb.length()); } 程序运行结果如下: abcdefghijklmnop sb.capacity = 21 sb.length = 16

34 (2)StringBuffer insert()
方法insert()用于在串缓冲区的指定位置offset处插入各种类型的数据。重载的方法有: StringBuffer insert(int offset,int i) StringBuffer insert(int offset,long l) StringBuffer insert(int offset,float f) StringBuffer insert(int offset,double d) 【例6.9】StringBuffer字符串插入操作。 class StringBufferInsert { public static void main(String args[]) { StringBuffer sb = new StringBuffer("abcde"); sb.insert(0, "012345"); System.out.println(sb); } } //程序运行结果如下:012345abcde

35 (3)StringBuffer delete(int start,int end)和 deleteCharAt(int index)
方法delete()用来从StringBuffer字符串对象中删去从start开始到end - 1结束的子字符串。例如: StringBuffer sb = new StringBuffer("aabbcc"); System.out.println(sb.delete(2,4)); // 输出为aacc 方法deleteCharAt()用来删除index处的字符。例如: StringBuffer sb = new StringBuffer("china"); System.out.println(sb.deleteCharAt(4)); // 输出为chin (4)StringBuffer reverse() 方法reverse()用于对StringBuffer类字符串对象进行颠倒操作。设原字符串的长度为n,新字符串中k位置的字符在原字符串中的位置为n-k-1。

36 【例6.10】对StringBuffer字符串进行颠倒操作。
class StringBufferReverse { public static void main(String args[]) { StringBuffer sb1 = new StringBuffer("abcde"); sb1.append("abcdefghij"); StringBuffer sb2 = sb1.reverse(); System.out.println(sb1); System.out.println(sb2); } 程序运行结果如下: jihgfedcbaedcba (5)void setCharAt(int index,char ch) 本方法的功能是设置指定位置index的字符值ch。

37 (6)StringBuffer replace(int start,int end,String str)
例如: StringBuffer sb = new StringBuffer("aaAaa"); sb.setCharAt(2,‘中’); // sb为aa中aa (6)StringBuffer replace(int start,int end,String str) 方法的功能是将StringBuffer对象字符串从start至end - 1处,用字符串str替换。例如: StringBuffer sb = new StringBuffer("********"); System.out.println(sb.replace(2,6,"Java")); 3.类StringBuffer对象的子字符串和字符 (1)void getChars(int srcBegin,int srcEnd,char[] dst, int dstBegin) 方法的功能是将StringBuffer对象字符串中字符复制到目标字符数组中去。复制的字符从srcBegin处开始,到srcEnd-1处结束. 复制字符的个数为srcEnd-srcBegin。字符被复制到目标数组的dstBegin至 dstBegin + (srcEnd-srcBegin) – 1处。

38 (2)String substring(int start)
例如: char a[]= {'*','*','*','*','*','*','*','*'}; StringBuffer sb = new StringBuffer("Java"); sb.getChars(0,4,a,2); System.out.println(a);// 输出为 **Java** (2)String substring(int start) 方法的功能是获取StringBuffer字符串对象从start处开始的子串。重载的方法String substring(int start,int end)用来获取StringBuffer字符串对象从start至end - 1处之间的子串。例如: StringBuffer sb = new StringBuffer("Java Programming"); System.out.println(sb.substring(5)); System.out.println(sb.substring(0,4)); // 输出为 Java

39 4.类型转换 (1)String toString()
在java.lang.Object中提供了方法toString将指定对象转换为字符串,与类Character、Integer、Boolean等一样,类StringBuffer也重写了方法toString(),可将类StringBuffer的对象转换成类String的对象。例如: StringBuffer sb = new StringBuffer("aabbcc"); String s = sb.toString(); System.out.println(s); // 输出为aabbcc

40 6.3 main方法的参数 在Java语言的类方法main()名后的括号中有String类的数组参数args,args可以用来接收Java命令行传送给Java应用程序的数据。所谓命令行参数是指在执行字节码文件时,在命令行上字节码文件名后给出的内容。例如: java HelloEcho How are you? 123 这里“How are you? 123”就是命令行参数,在Java应用程序中通过args来得到并处理这些内容。命令行参数有多个时,一般用空格来分隔,如上述的命令行参数有4个。在Java应用程序中,将这些参数一个一个按顺序存入类String的数组args,第一个参数存入args[0],第二个参数存入args[1]等等。

41 若要将包含多个空格的单词作为一个字符串,可用引号括起来。例如:
按照上述命令行的写法,“How”存入args[0],“are” 存入args[1], “you?” 存入args[2],“123”存入args[3]。注意:它们都是String类的对象。 若要将包含多个空格的单词作为一个字符串,可用引号括起来。例如: java HelloEcho " How are you?" 123 【例6.11】显示所有命令行参数。 class CommandLine { public static void main(String args[]) { for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); }

42 若执行程序的命令为: 则程序运行结果为: 【例6.12】用符号“#”画一个宽为w高为h的空心方框。w和h用命令行参数方式提供。
java CommandLine how are you? 则程序运行结果为: how are you? 【例6.12】用符号“#”画一个宽为w高为h的空心方框。w和h用命令行参数方式提供。 public class DoRect{ public static void main(String args[]){ int w = Integer.valueOf(args[0]).intValue(); int h = Integer.valueOf(args[1]).intValue(); Rectangle myrect = new Rectangle(w,h); myrect.drawRect(); }

43 class Rectangle{ int width,height,area; public Rectangle(int w,int h){ width = w; height = h; area = getArea(w,h); } protected int getArea(int w,int h){ int a; a = w * h; return a; public void drawRect(){ int i,j;

44 for(i = width;i > 0;i --)System.out.print("#");
System.out.println(); for(i = height - 2;i > 0;i --){ System.out.print("#"); for(j = width - 2;j > 0;j --) System.out.print(" "); } System.out.println("");

45 6.4 字符串应用举例 【例6.13】用命令行方式提供1至3个整数,按顺序分别为年、月、日数据。若仅提供一个整数,则为年号,程序判断该年是否为闰年;若提供两个整数,则为年号、月号,程序输出为该年月的天数;若提供三个整数,则为年、月、日数据,程序输出这一天是星期几。若未提供任何数据或提供的数据个数超过三个,则程序输出出错信息并给出程序的使用方法。

46 if(args.length < 1 || args.length > 3){
class StringExam{ public static void main(String args[]){ String weekname = "日一二三四五六",s,leap; int y,m,d,t = 0,w = 0,i; if(args.length < 1 || args.length > 3){ System.out.println("参数个数错误!"); System.out.println("请重新启动程序," + "在命令行上提供1至3个整数参数!"); }else{ y = Integer.valueOf(args[0]).intValue(); leap = (y % 400==0 || y % 4==0 && y % 100 != 0)?"闰":"平";

47 if(args.length == 3){ m = Integer.valueOf(args[1]).intValue(); d = Integer.valueOf(args[2]).intValue(); w = y + (y-1)/ 4 - (y-1)/ (y-1)/ 400; for(i = 1;i <= m - 1; i++) t += month_num(i,leap); w = (w + t + d - 1) % 7;

48 s = weekname.substring(w,w + 1);
System.out.println(y + " 年 "+ m +" 月 "+ d + " 日是星期"+ s +"。" ); } else if(args.length == 2){ m = Integer.valueOf(args[1]).intValue(); t = month_num(m,leap); System.out.println(y + “ 年 ”+ m +“ 月有 ” + t +" 天。"); else { System.out.println(y + " 年是" + leap + "年。");

49 static int month_num(int m,String b){
//求各月的天数 String big = " ", s = String.valueOf(m); int n,w; if(m == 2) n = (b == "闰") ? 29 : 28; else{ w = big.indexOf(s); // 大月天数为31天 n = 31; if(w == -1) n--; // 小月在大月的天数上减去1天 } return n;

50 下面是三次运行程序的结果: (1)命令行参数为: 2005 程序输出:2005 年是平年。 (2)命令行参数为: 2005 2
程序输出:2005 年 2 月有 28 天。 (3)命令行参数为: 程序输出:2005 年 3 月 10 日是星期四。


Download ppt "第6章 字符串处理."

Similar presentations


Ads by Google