44
第第第 第第第第第第

第四章 数组与字符串

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: 第四章 数组与字符串

第四章 数组与字符串

Page 2: 第四章 数组与字符串

概念 数组是一组同类型的变量或对象的集合

数组的类型可以是基本类型,或类和接口 数组中每个元素的类型相同 引用数组元素通过数组名 [ 下标 ] 数组下标 ( 数组的索引 ) 从 0 开始

数组是一种特殊的对象 (Object) 定义类型 ( 声明 ) 创建数组 ( 分配内存空间 ) : new

一维数组、多维数组

Page 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]);

Page 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];

Page 5: 第四章 数组与字符串

一维数组 一维数组的初始化

方式一 : 在声明数组的同时对数组初始化 格式 : 类型 数组名 [] = { 元素 1[, 元素 2 ……]}; int a[] = {1, 2, 3, 4, 5};

方式二 : 声明和创建数组后对数组初始化 一维数组的引用 数组名 [ 下标 ]

Page 6: 第四章 数组与字符串

【示例 4-1 】 ArrayTest.java

public class ArrayTest {public static void main(String[] args) {

int i; int a[]=new int[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

Page 7: 第四章 数组与字符串

【示例 4-2 】 classFibonacci.java

public class ClassFibonacci {public static void main(String[] args) {

int i; int f[]=new int[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]); }

}

程序运行结果:

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

Page 8: 第四章 数组与字符串

多维数组 数组的数组

Arrays of Arrays 例 : 表格 ( 行和列 )

以二维数组为例

Page 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 个元素

Page 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[][];

Page 11: 第四章 数组与字符串

二维数组 二维数组的初始化

每个元素单独进行赋值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();}

}}

最高维数组长度

1 0 00 1 00 0 1

Page 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] 下标为非负的整型常数

Page 13: 第四章 数组与字符串

【示例 4-3 】 MatrixMultiply.java

public class MatrixMultiply{ public static void main(String args[]){

int i,j,k; int a[][]=new int[2][3]; int b[][]={{1,5,2,8},{5,9,10,-3},{2,7,-5,-18}}; int c[][]=new int[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]; // 矩阵相乘}

}

Page 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

Page 15: 第四章 数组与字符串

【示例 4-4 】 TwoArrayAgain.java 】public class TwoArrayAgain{

public static void main(String[] args){int twoArray[][] = new int[4][]; // 声明二维数

组twoArray[0] = new int[1]; // 定义每

一行twoArray[1] = new int[2];twoArray[2] = new int[3];twoArray[3] = new int[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

Page 16: 第四章 数组与字符串

对数组对象的操作 (Arrays) 全部是静态方法

public static int binarySearch(type[] a, type key) public static int binarySearch(type[] a , int fromIndex , i

nt 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, ty

pe val) public static void sort(type[] a) public static void sort(type[] a , int fromIndex , int toInd

ex) public static void type[] copyOf(type[] original , int newLe

ngth) public static void type[] copyOfRange(type[] original , int

from , int to)

boolean[], char[], type[], short[], int[], long[], double[], float[]Object[]

Page 17: 第四章 数组与字符串

字符串操作类 两个类

java.lang.String 类 java.lang.StringBuffer 类

不同的应用场合

Page 18: 第四章 数组与字符串

字符串操作类 java.lang.String 类—字符串 / 字符序列

构造方法 public String() public String(byte bytes[] ) public String(byte bytes[], int offset, int count) public String(char value[] ) public String(char value [], int offset, int count) public String(String original)

Page 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 = “ 语言” ;

Page 20: 第四章 数组与字符串

字符串操作类 java.lang.String 类—字符串 / 字符序列

判断字符串相等的方法 public boolean equals(Object anObject) public boolean equalsIgnoreCase(String anotherStri

ng) public int compareTo(String anotherString) public int compareToIgnoreCase(String str) 基本功

能同上,仅仅在判断时不考虑大小写

Page 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(s

2));运行结果:false true 32 0

Page 22: 第四章 数组与字符串

字符串操作类 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

));

System.out.println(s2 == s4);System.out.println(s2.equals(s4));System.out.println(s2.compareTo(s4

)); 运行结果 :

falsetrue 0

truetrue0

falsetrue0

结论:1. String s1 = “abc”; 字符串常量对象 (immutable) String s2 = “abc”; 不同常量对象共享同一对象2. 其他字符串对象则可理解为对字符串常量对象进行了 一层包装

Page 23: 第四章 数组与字符串

【示例 4-9 】 EqualsDemo.java

public class EqualsDemo {public static void 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)); }

}程序运行结果:

truefalsetruetrue

Page 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)

Page 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));

运行结果:66java语言JavA语言j

Page 26: 第四章 数组与字符串

字符串操作类 java.lang.String 类—字符串 / 字符序列

字符串前缀 (prefix)/ 后缀 (suffix) 的判断 public boolean startsWith(String prefix)

判断字符串是否以一特定的字符串开头 public boolean startsWith(String prefix, int s

tartIndex) public boolean endsWith(String suffix)

判断字符串是否以一特定的字符串结尾

System.out.println("java 语言 ".startsWith("java"));

System.out.println("java 语言 ".startsWith("ava", 1));

System.out.println("java 语言 ".endsWith(" 语言 "));

Page 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 fromInd

ex)

从前往后

从后往前

Page 28: 第四章 数组与字符串

字符串操作类 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));

运行结果:13142242

java 语言

Page 29: 第四章 数组与字符串

字符串操作类 java.lang.String 类—字符串 / 字符序列

字符串转变为数组 public byte[] getBytes()

将字符串转变为一个字节数组 public byte[] getBytes(String charsetName) t

hrows UnsupportedEncodingException 按特定的字符编码格式将字符串转变为一个字节数组

public char[] toCharArray() 将字符串转变为一个字符数组

Page 30: 第四章 数组与字符串

字符串操作类 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

中文Windows 操作系统 : 默认字符集 GB2312其他系统 : 默认字符集 ISO-8859-1

Page 31: 第四章 数组与字符串

字符串操作类 java.lang.String 类—字符串 / 字符序列

一些静态方法 public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(float f) public static String valueOf(double d)

其他方法 public String trim() 将字符串头尾的空格字符删除 public String toLowerCase() 字符串中字符转为小写 public String toUpperCase() 字符串中字符转为大写

Page 32: 第四章 数组与字符串

字符串操作类 java.lang.String 类—字符串 / 字符序列

其他方法 public String concat(String str) 连接字符串 "cares".concat("s") return "caress" "to".concat("get").con

cat("her") return "together" public String replace(char oldChar, char newChar) 在字符串

中进行字符替换 "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[] tar

get, int targetStart

Page 33: 第四章 数组与字符串

字符串操作类 字符串的连接运算 (Concatenation)

“java” 和“语言”1. String s = “java” + “ 语言” ;2. String s = “java”.concat(“ 语言” );3. StringBuffer buffer = new StringBuffer(“j

ava”); buffer.append(“ 语言” ); String s = buffer.toString();

常用第 1 种和第 3 种方法

Page 34: 第四章 数组与字符串

【示例 4-7 】: StringDemo.java

public class StringDemo {public static void 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

Page 35: 第四章 数组与字符串

【示例 4-8 】 CharAtString.java

public class CharAtString { public static void 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]);}

}

程序运行结果:字符串内容 : 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.

Page 36: 第四章 数组与字符串

字符串操作类 java.lang.StringBuffer 类

一个可变 (mutable)/动态的字符序列 构造方法

public StringBuffer() public StringBuffer(int length) public StringBuffer(String str)

主要方法 添加 (append) 和插入 (insert, 指定位置 )

public StringBuffer append(参数 ) public StringBuffer insert(int beginIndex, appendArguments ) boolean, char, char[], double, float, int, long, String

转换为字符串 - public String toString()

Page 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.

Page 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, ch

ar[] target, int targetStart

Page 39: 第四章 数组与字符串

字符串操作类 java.lang.StringBuffer 类

其他方法 delete(int startIndex,int endIndex) deleteCharAt(int index) replace(int startIndex,int endIndex,string str) public StringBuffer reverse( )

Page 40: 第四章 数组与字符串

命令行参数 JAVA 应用程序的主方法 (程序的入口 )

public static void main (String args[]) {…}public static void main (String[] args) {…}

命令行参数在启动 JAVA 应用程序时一次性地传递多个参数

C:\java 类名 参数 参数 ……空格将参数分开若参数包含空格,用双引号引起来

Page 41: 第四章 数组与字符串

命令行参数 示例 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 Test0

C:\>

C:\>java Test s1 s22s1s2

C:\>

C:\>java Test “s1 s2”1s1 s2

C:\>

Page 42: 第四章 数组与字符串

命令行参数 示例 2

class Test {public static void main(String[] args) {

for (int i = 0; i < args.length; i++) System.out.println(“args[“+i+”]=

“+args[i]);}

}

C:\>java Test s1 s2 s3args[0]=s1args[1]=s2args[2]=s3

C:\>

Page 43: 第四章 数组与字符串

命令行参数命令行参数的转换

java.lang.Byte类public static byte parseByte(String s) throws NumberFormatException

java.lang.Integer类public static int parseInt(String s) throws Nu

mberFormatException……

Page 44: 第四章 数组与字符串

命令行参数 示例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);

}}

C:\>java Test 1 23

C:\>