1 / 44

第四章 数组与字符串

第四章 数组与字符串. 概念. 数组是一组同类型的变量或对象的集合 数组的类型可以是 基本类型 ,或类和接口 数组中每个元素的类型相同 引用数组元素通过 数组名 [ 下标 ] 数组下标 ( 数组的索引 ) 从 0 开始 数组是一种特殊的对象 (Object) 定义类型 ( 声明 ) 创建数组 ( 分配内存空间 ) : new 一维数组、多维数组. 一维数组. 一维数组的元素只有一个下标变量 例 : A[1], c[3] 一维数组的声明 方法 1: 类型 数组名 [];

hayes-snow
Download Presentation

第四章 数组与字符串

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第四章 数组与字符串

  2. 概念 • 数组是一组同类型的变量或对象的集合 • 数组的类型可以是基本类型,或类和接口 • 数组中每个元素的类型相同 • 引用数组元素通过数组名[下标] • 数组下标(数组的索引)从0开始 • 数组是一种特殊的对象(Object) • 定义类型 (声明) • 创建数组 (分配内存空间) : new • 一维数组、多维数组

  3. 一维数组 • 一维数组的元素只有一个下标变量 • 例: A[1], c[3] • 一维数组的声明 • 方法1: 类型 数组名[]; • String args[]; int a[]; double amount[]; char c[]; • 方法2: 类型[] 数组名; • String[] args; int[] a; double[] amount; char[] c; • 注意 • 类型是数组中元素的数据类型(基本和构造类型) • 数组名是一个标识符 • 数组声明后不能被访问,因未为数组元素分配内存空间 double[] d; System.out.println(d[0]);

  4. 一维数组 • 数组的创建 • 用new来创建数组 • 为数组元素分配内存空间,并对数组元素进行初始化 • 格式: 数组名 = new 类型[数组长度] • 例: a = new int[3]; • 声明和创建的联用: int[] a = new int[3]; • 默认赋初值 • 整型初值为0 int[] i = new int[3]; • 实型初值为0.0 float[] f = new float[3]; • 布尔型初值为false boolean[] b = new boolean[3];

  5. 一维数组 • 一维数组的初始化 • 方式一: 在声明数组的同时对数组初始化 • 格式: 类型 数组名[] = {元素1[, 元素2 ……]}; • int a[] = {1, 2, 3, 4, 5}; • 方式二: 声明和创建数组后对数组初始化 • 一维数组的引用 数组名[下标]

  6. 【示例4-1】ArrayTest.java publicclass ArrayTest { publicstaticvoid main(String[] args) { int i; int a[]=newint[5]; for(i=0;i<5;i++) a[i]=i; for(i=a.length-1;i>=0;i--) System.out.println("a["+i+"]="+a[i]); } } 程序运行结果: a[4]=4 a[3]=3 a[2]=2 a[1]=1 a[0]=0

  7. 程序运行结果: F[1]=1 F[2]=1 F[3]=2 F[4]=3 F[5]=5 F[6]=8 F[7]=13 F[8]=21 F[9]=34 F[10]=55 【示例4-2】classFibonacci.java publicclass ClassFibonacci { publicstaticvoid main(String[] args) { int i; int f[]=newint[10]; f[0]=f[1]=1; for(i=2;i<10;i++) f[i]=f[i-1]+f[i-2]; for(i=1;i<=10;i++) System.out.println("F["+i+"]="+f[i-1]); } }

  8. 多维数组 • 数组的数组 • Arrays of Arrays • 例: 表格(行和列) • 以二维数组为例

  9. 二维数组 • 二维数组的声明 • 类型 数组名[][], 例 int a[][]; • 数组声明后不能被访问,因未为数组元素分配内存空间 • 二维数组的创建 • 方法一: 直接分配空间 例 int a[][] = new int[2][3]; a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] 两个一维数组,每个数组包含3个元素

  10. 二维数组 • 二维数组的创建 • 方法二: 从最高维开始,为每一维分配空间 例 int c[][] = new int[2][]; c[0] = new int[4]; c[1] = new int[3]; c[0][0] c[0][1] c[0][2] c[0][3] c[1][0] c[1][1] c[1][2] • 注: 为数组分配空间需指定维数大小,至少最高维(最左边)大小 • 错误: int b[][] = new int[][];

  11. 二维数组 1 0 0 0 1 0 0 0 1 • 二维数组的初始化 • 每个元素单独进行赋值 class Test { public static void main (String args[]) { int a[][] = new int[3][3]; a[0][0]=1;a[1][1]=1;a[2][2]=1; System.out.println(“数组a: ”); for (int i=0; i< a.length; i++){ for (int j=0; j<a[i].length; j++) System.out.print(a[i][j]+“ ”); System.out.println(); } } } 最高维数组长度

  12. 二维数组 • 二维数组的初始化 • 声明数组的同时初始化 例 int a[][] = {{1,2,3}, {3,4,5}}; a[0][0]=1 a[0][1]=2 a[0][2]=3 a[1][0]=3 a[1][1]=4 a[1][2]=5 • 对数组元素的引用 • 数组名[下标1] [下标2] • 下标为非负的整型常数

  13. 【示例4-3】MatrixMultiply.java publicclass MatrixMultiply{ publicstaticvoid main(String args[]){ int i,j,k; int a[][]=newint[2][3]; int b[][]={{1,5,2,8},{5,9,10,-3},{2,7,-5,-18}}; int c[][]=newint[2][4]; for(i=0;i<2;i++) for(j=0;j<3;j++) a[i][j]=(i+1)*(j+2); for(i=0;i<2;i++){ for(j=0;j<4;j++){ c[i][j]=0; for(k=0;k<3;k++) c[i][j]+=a[i][k]*b[k][j]; //矩阵相乘 } }

  14. 【示例4-3】MatrixMultiply.java System.out.println("\n***MatrixA***"); for(i=0;i<2;i++){ for(j=0;j<3;j++) System.out.print(a[i][j]+""); System.out.println(); } System.out.println("\n***MatrixB***"); for(i=0;i<3;i++){ for(j=0;j<4;j++) System.out.print(b[i][j]+""); System.out.println(); } System.out.println("\n***MatrixC***"); for(i=0;i<2;i++){ for(j=0;j<4;j++) System.out.print(c[i][j]+""); System.out.println(); } } } 程序运行结果: ***MatrixA*** 2 3 4 4 6 8 ***MatrixB*** 1 5 2 8 5 9 10 -3 2 7 -5 -18 ***MatrixC*** 25 65 14 -65 50 130 28 -130

  15. 【示例4-4】TwoArrayAgain.java】 publicclass TwoArrayAgain{ publicstaticvoid main(String[] args){ int twoArray[][] = newint[4][]; //声明二维数组 twoArray[0] = newint[1]; // 定义每一行 twoArray[1] = newint[2]; twoArray[2] = newint[3]; twoArray[3] = newint[4]; int i, j, k = 0; for(i=0; i<twoArray.length; i++) for(j=0;j<twoArray[i].length ;j++,k++){ twoArray [i][j] = k; } for(i=0; i<twoArray.length; i++){ for(j=0;j<twoArray[i].length;j++) { System.out.print(twoArray[i][j] + " "); } System.out.println(); } } } 程序运行结果: 0 1 2 3 4 5 6 7 8 9

  16. boolean[], char[], type[], short[], int[], long[], double[], float[] Object[] 对数组对象的操作(Arrays) • 全部是静态方法 • public static int binarySearch(type[] a, type key) • public static int binarySearch(type[] a,int fromIndex,int toIndex,type key) • public static boolean equals(type[] a, type[] a2) • public static void fill(type[] a, type val) • public static void fill(type[] a, int fromIndex, int toIndex, type val) • public static void sort(type[] a) • public static void sort(type[] a,int fromIndex,int toIndex) • public static void type[] copyOf(type[] original,int newLength) • public static void type[] copyOfRange(type[] original,int from,int to)

  17. 字符串操作类 • 两个类 • java.lang.String类 • java.lang.StringBuffer类 • 不同的应用场合

  18. 字符串操作类 • java.lang.String类—字符串/字符序列 • 构造方法 • public String() • public String(byte bytes[]) • public String(bytebytes[], intoffset, intcount) • public String(char value[]) • public String(charvalue [], intoffset, intcount) • public String(Stringoriginal)

  19. 字符串操作类 • java.lang.String类—字符串/字符序列 • 构造方法的使用 String s = new String(); char c[] = {‘a’, ‘b’, ‘c’}; String s = new String(c); char c[] = {‘语’, ‘言’}; String s = new String(c); byte b[] = {97, 98, 99}; String s = new String(b); String s = “abc”; String s = “语言”;

  20. 字符串操作类 • java.lang.String类—字符串/字符序列 • 判断字符串相等的方法 • public boolean equals(Object anObject) • public boolean equalsIgnoreCase(String anotherString) • public int compareTo(String anotherString) • public int compareToIgnoreCase(String str) 基本功能同上,仅仅在判断时不考虑大小写

  21. 字符串操作类 • java.lang.String类—字符串/字符序列 • 判断字符串相等的方法 String s1 = "java语言"; String s2 = "JavA语言"; System.out.println(s1.equals(s2)); System.out.println(s1.equalsIgnoreCase(s2)); System.out.println(s1.compareTo(s2)); System.out.println(s1.compareToIgnoreCase(s2)); 运行结果: false true 32 0

  22. System.out.println(s2 == s4); System.out.println(s2.equals(s4)); System.out.println(s2.compareTo(s4)); 字符串操作类 • 结论: • String s1 = “abc”;  字符串常量对象 (immutable) • String s2 = “abc”; 不同常量对象共享同一对象 • 其他字符串对象则可理解为对字符串常量对象进行了 • 一层包装 运行结果: false true 0 true true 0 false true 0 • java.lang.String类—字符串/字符序列 String s1 = new String(“java”); String s2 = new String(“java”); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); System.out.println(s1.compareTo(s2)); String s3 = “java”; String s4 = “java”; System.out.println(s3== s4); System.out.println(s3.equals(s4)); System.out.println(s3.compareTo(s4));

  23. 【示例4-9】EqualsDemo.java publicclass EqualsDemo { publicstaticvoid main(String[] args) { String s1="aaaa"; String s2=new String("aaaa"); String s3="aaaa"; String s4=new String("aaaa"); System.out.println(s1==s3); //字符串常量引用同一常量池中的对象 System.out.println(s2==s4); //字符串对象将分别创建 System.out.println(s1.equals(s2)); System.out.println(s3.equals(s4)); } } 程序运行结果: true false true true

  24. 字符串操作类 • java.lang.String类—字符串/字符序列 • 获取长度 • public int length() 字符串的长度,即包含多少个字符 • 获取特定子串(substring)和字符 • public String substring(int beginIndex) • public String substring(int beginIndex, int endIndex) • beginIndex: 起始索引位置(包含) • endIndex: 结束索引位置(不包含) • public char charAt(int index)

  25. 字符串操作类 • java.lang.String类—字符串/字符序列 • 方法举例 String s1 = "java语言"; String s2 = "JavA语言"; System.out.println(s1.length()); System.out.println(s2.length()); System.out.println(s1.substring(0, 4)); System.out.println(s1.substring(4)); System.out.println(s2.substring(0, 4)); System.out.println(s2.substring(4)); System.out.println(s1.charAt(0)); 运行结果: 6 6 java 语言 JavA 语言 j

  26. 字符串操作类 • java.lang.String类—字符串/字符序列 • 字符串前缀(prefix)/后缀(suffix)的判断 • public boolean startsWith(String prefix) 判断字符串是否以一特定的字符串开头 • public boolean startsWith(String prefix, int startIndex) • public boolean endsWith(String suffix) 判断字符串是否以一特定的字符串结尾 System.out.println("java语言".startsWith("java")); System.out.println("java语言".startsWith("ava", 1)); System.out.println("java语言".endsWith("语言"));

  27. 前 往 后 从 后 往 前 字符串操作类 • java.lang.String类—字符串/字符序列 • 查询特定字符/字符串的位置 • public int indexOf(int ch) 该字符在字符串中第一次出现位置的索引值;否则返回-1 • public int indexOf(int ch, int fromIndex) • public int indexOf(String str) • public int indexOf(String str, int fromIndex) • public int lastIndexOf(int ch) • public int lastIndexOf(int ch, int fromIndex) • public int lastIndexOf(String str) • public int lastIndexOf(String str, int fromIndex)

  28. java语言 字符串操作类 • java.lang.String类—字符串/字符序列 • 方法举例 String s = “java语言”; System.out.println(s.indexOf(‘a’)); System.out.println(s.indexOf(‘a’, 2)); System.out.println(s.indexOf(“a”)); System.out.println(s.indexOf(“语言”)); System.out.println(s.lastIndexOf(‘a’)); System.out.println(s.lastIndexOf(‘v’, 1)); System.out.println(s.lastIndexOf(“语言”)); System.out.println(s.lastIndexOf(“v”, 2)); 运行结果: 1 3 1 4 2 2 4 2

  29. 字符串操作类 • java.lang.String类—字符串/字符序列 • 字符串转变为数组 • public byte[] getBytes() 将字符串转变为一个字节数组 • public byte[] getBytes(StringcharsetName) throws UnsupportedEncodingException 按特定的字符编码格式将字符串转变为一个字节数组 • public char[] toCharArray() 将字符串转变为一个字符数组

  30. 中文Windows操作系统: 默认字符集 GB2312 其他系统: 默认字符集 ISO-8859-1 字符串操作类 • java.lang.String类—字符串/字符序列 • 方法举例 String s = "java语言"; char[] c = s.toCharArray(); System.out.println(c.length); byte[] b = s.getBytes(); System.out.println(b.length); b = s.getBytes("ISO8859-1"); System.out.println(b.length); 运行结果: 6 8 6

  31. 字符串操作类 • java.lang.String类—字符串/字符序列 • 一些静态方法 • public static String valueOf(booleanb) • public static String valueOf(charc) • public static String valueOf(inti) • public static String valueOf(longl) • public static String valueOf(floatf) • public static String valueOf(doubled) • 其他方法 • public String trim() 将字符串头尾的空格字符删除 • public String toLowerCase() 字符串中字符转为小写 • public String toUpperCase() 字符串中字符转为大写

  32. 字符串操作类 • java.lang.String类—字符串/字符序列 • 其他方法 • public String concat(Stringstr) 连接字符串 "cares".concat("s")  return "caress""to".concat("get").concat("her")  return "together" • public String replace(charoldChar, charnewChar) 在字符串中进行字符替换 "mesquite in your cellar".replace('e', 'o')  return "mosquito in your collar” "JonL".replace('q', 'x') return "JonL" (no change) • toString() 返回对象的字符串表示 • public void getChars (int sourceStart, int sourceEnd, char[] target, int targetStart

  33. 字符串操作类 • 字符串的连接运算(Concatenation) • “java”和“语言” • String s = “java” + “语言”; • String s = “java”.concat(“语言”); • StringBuffer buffer = new StringBuffer(“java”); buffer.append(“语言”); String s = buffer.toString(); • 常用第1种和第3种方法

  34. 【示例4-7】: StringDemo.java publicclass StringDemo { publicstaticvoid main(String[] args) { String text = "hello"; System.out.println("字符串内容: " + text); System.out.println("字符串长度: " + text.length()); System.out.println("等于hello? " +text.equals("hello")); System.out.println("转为大写: " +text.toUpperCase()); System.out.println("转为小写: " +text.toLowerCase()); } } 程序运行结果: 字符串内容: hello 字符串长度: 5 等于hello? true 转为大写: HELLO 转为小写: hello

  35. 程序运行结果: 字符串内容: One's left brain has nothing right. One's right brain has nothing left. 第一个left: 6 最后一个left: 66 字符Array 内容: One's left brain has nothing right. One's right brain has nothing left. 【示例4-8】CharAtString.java publicclass CharAtString { publicstaticvoid main(String[] args) { String text = "One's left brain has nothing right.\n" + "One's right brain has nothing left.\n"; System.out.println("字符串内容: "); for(int i = 0; i < text.length(); i++) System.out.print(text.charAt(i)); System.out.println("\n 第一个left: " +text.indexOf("left")); System.out.println("最后一个left: " +text.lastIndexOf("left")); char[] charArr = text.toCharArray(); System.out.println("\n 字符Array 内容: "); for(int i = 0; i < charArr.length; i++) System.out.print(charArr[i]); } }

  36. 字符串操作类 • java.lang.StringBuffer类 • 一个可变(mutable)/动态的字符序列 • 构造方法 • public StringBuffer() • public StringBuffer(int length) • public StringBuffer(String str) • 主要方法 • 添加(append)和插入(insert, 指定位置) • public StringBuffer append(参数) • public StringBuffer insert(intbeginIndex, appendArguments ) • boolean, char, char[], double, float, int, long, String • 转换为字符串 - public String toString()

  37. 字符串操作类 • java.lang.StringBuffer类—方法举例 String s = "java语言"; StringBuffer buffer = new StringBuffer(s); buffer.append(“easy”); buffer.insert(6, “ is “); s = buffer.toString(); System.out.println(s); 运行结果: java语言 is easy.

  38. 字符串操作类 • java.lang.StringBuffer类 • 主要方法 • 获取和修改串长度的方法 • public int length() • public int capacity() • public void setLength(int newLength) • 获取字符和修改字符的方法 • public charAt(int index) • public setCharAt(int index, char ch) • public void getChars (int sourceStart, int sourceEnd, char[] target, int targetStart

  39. 字符串操作类 • java.lang.StringBuffer类 • 其他方法 • delete(int startIndex,int endIndex) • deleteCharAt(int index) • replace(int startIndex,int endIndex,string str) • public StringBuffer reverse( )

  40. 命令行参数 • JAVA应用程序的主方法(程序的入口) • public static void main (String args[]) {…} • public static void main (String[] args) {…} • 命令行参数 • 在启动JAVA应用程序时一次性地传递多个参数 • C:\java 类名 参数 参数 …… • 空格将参数分开 • 若参数包含空格,用双引号引起来

  41. 命令行参数 C:\>java Test s1 s2 2 s1 s2 C:\> • 示例1 class Test { public static void main(String[] args) { int len = args.length; System.out.println(len); for (int i = 0; i < len; i++) System.out.println(args[i]); } } C:\>java Test “s1 s2” C:\>java Test 0 C:\> 1 s1 s2 C:\>

  42. 命令行参数 C:\>java Test s1 s2 s3 args[0]=s1 args[1]=s2 args[2]=s3 C:\> • 示例 2 class Test { public static void main(String[] args) { for (int i = 0; i < args.length; i++) System.out.println(“args[“+i+”]=“+args[i]); } }

  43. 命令行参数 • 命令行参数的转换 • java.lang.Byte类 • public static byte parseByte(Strings) throws NumberFormatException • java.lang.Integer类 • public static int parseInt(Strings) throws NumberFormatException • ……

  44. 命令行参数 C:\>java Test 1 2 3 C:\> • 示例 import java.lang.NumberFormatException; class Test { public static void main(String[] args) throws NumberFormatException { int sum = 0; for (int i = 0; i < args.length; i++) sum = sum + Integer.parseInt(args[i]); System.out.println(sum); } }

More Related