第4章 数组、字符串、向量

Java系列文章

第1章 绪论
第2章 结构化程序设计
第4章 数组、字符串、向量
第6章 异常处理、递归


前言

有关Java数组、字符串、向量的基础知识
在这里插入图片描述


提示:以下是本篇文章正文内容,大家可以选择自己感兴趣部分阅读

一、数组

前情提要:数据类型回顾

在这里插入图片描述

数组概念

数组是具有相同数据类型的一组数据的集合

举个例子的话
就是 [0, 1, 2, 3, 4]
这个数组中拥有整形(int)数据1、2、3、4

而在数据结构中

在这里插入图片描述

数组的组成

(1)数据元素
(2)数组长度length (元素个数)

一维数组

在这里插入图片描述

12345

在这里插入图片描述

1.12.23.34.45.5

在这里插入图片描述

A,B,C,D,E

在这里插入图片描述

"你好""世界"

一维数组声明

单个

int[ ] c;                  int c[ ];           
String[ ] names;           String names[ ];

多个

String a[], b[], c[]; 
String a[], b, c;    // a是数组,b和c是字符串而非数组

一维数组创建

int c[];  //声明数组                   
c = new int[5];  //创建数组对象,分配内存空间

或者

int c[] = new int[5];

例子,

int c[] = {1, 2, 3, 4, 5};  //创建含有5个整数元素的数组                   
char [] a={‘a’, ‘b’, ‘c’}; //创建含有3个字符元素的数组

访问数组元素

String s[] = new String(2);//创建字符串数组,长度为2

s[0] = new String("你好");//访问第一个元素
s[1] = new String("世界");//访问第二个元素

等价于

String s[]={new String("你好"), new String("世界")}

注意事项

基本数据类型的元素初始化为0值或false
非基本数据类型的元素初始化为null 。
当访问数组的某个元素时,
下标永远不要低于0
下标永远要比数组元素个数(length)小
当数组下标超过length-1,Java 产生下标越界错误ArrayIndexOutOfBoundsException

多维数组

实质上与一维数组类似

如一个二维数组的声明

int [][] marx;  //声明二维数组变量marx

以下是对一个二维数组的介绍

int[ ][ ] a = new int[3][4];
//创建一个二维数组,并将其引用赋值给变量a
//数组matrix的元素个数是3
//并且数组a的每个元素都是包含4个元素的一维数组

在这里插入图片描述
在这里插入图片描述
多维数组代码范例

class J_FillArray
{
    public static void main (String args[])
    { 
	int[ ][ ] matrix = new int[2][3]; 
	for (int row=0; row < 2; row++)
		{ 
  		for (int col=0; col < 3; col++)
    		{
	      matrix[row][col] = row + col;
	      System.out.println(“第”+ (row+1)+“行”+“第”+ (col+1)+“列值"+matrix[row][col]); 
    		} // 内部for循环结束
 		
 		} // 外部for循环结束
    
    } // 方法main结束

} // 类J_FillArray结束

推荐文章Java模拟一个数组

二、字符串

简单的字符串

"Hello World! ","愿世界和平"

构造

字符串对象s1指向空字符串

 String s1 = new String();  

字符串对象s2不指向任何字符串

 String s2 = null; 

利用字符串创建新字符串

 String s3 = new String("are"); 

利用字符数组创建字符串

 char ss[] = new char []{'a','b','c'}; 
 String s5 = new String(ss);  
public class StringDemo{
   public static void main(String args[]){
      char[] helloArray = { 'r', 'u', 'n', 'o', 'o', 'b'};
      String helloString = new String(helloArray);  
      System.out.println( helloString );
   }
}

字符串长度

public class StringDemo {
    public static void main(String args[]) {
        String site = "www.runoob.com";
        int len = site.length();
        System.out.println( "菜鸟教程网址长度 : " + len );
   }
}

连接字符串

1 concat

string1.concat(string2);

2 +号连接

"Hello," + " runoob" + "!"

字符串方法

详情见菜鸟教程Java String类

1	char charAt(int index)
返回指定索引处的 char 值。
2	int compareTo(Object o)
把这个字符串和另一个对象比较。
3	int compareTo(String anotherString)
按字典顺序比较两个字符串。
4	int compareToIgnoreCase(String str)
按字典顺序比较两个字符串,不考虑大小写。
5	String concat(String str)
将指定字符串连接到此字符串的结尾。
6	boolean contentEquals(StringBuffer sb)
当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。
7	static String copyValueOf(char[] data)
返回指定数组中表示该字符序列的 String8	static String copyValueOf(char[] data, int offset, int count)
返回指定数组中表示该字符序列的 String9	boolean endsWith(String suffix)
测试此字符串是否以指定的后缀结束。
10	boolean equals(Object anObject)
将此字符串与指定的对象比较。
11	boolean equalsIgnoreCase(String anotherString)
将此 String 与另一个 String 比较,不考虑大小写。
12	byte[] getBytes()
 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
13	byte[] getBytes(String charsetName)
使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
14	void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
将字符从此字符串复制到目标字符数组。
15	int hashCode()
返回此字符串的哈希码。
16	int indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引。
17	int indexOf(int ch, int fromIndex)
返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
18	int indexOf(String str)
 返回指定子字符串在此字符串中第一次出现处的索引。
19	int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
20	String intern()
 返回字符串对象的规范化表示形式。
21	int lastIndexOf(int ch)
 返回指定字符在此字符串中最后一次出现处的索引。
22	int lastIndexOf(int ch, int fromIndex)
返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
23	int lastIndexOf(String str)
返回指定子字符串在此字符串中最右边出现处的索引。
24	int lastIndexOf(String str, int fromIndex)
 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
25	int length()
返回此字符串的长度。
26	boolean matches(String regex)
告知此字符串是否匹配给定的正则表达式。
27	boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
测试两个字符串区域是否相等。
28	boolean regionMatches(int toffset, String other, int ooffset, int len)
测试两个字符串区域是否相等。
29	String replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
30	String replaceAll(String regex, String replacement)
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
31	String replaceFirst(String regex, String replacement)
 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
32	String[] split(String regex)
根据给定正则表达式的匹配拆分此字符串。
33	String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串。
34	boolean startsWith(String prefix)
测试此字符串是否以指定的前缀开始。
35	boolean startsWith(String prefix, int toffset)
测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
36	CharSequence subSequence(int beginIndex, int endIndex)
 返回一个新的字符序列,它是此序列的一个子序列。
37	String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。
38	String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。
39	char[] toCharArray()
将此字符串转换为一个新的字符数组。
40	String toLowerCase()
使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
41	String toLowerCase(Locale locale)
 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
42	String toString()
 返回此对象本身(它已经是一个字符串!)。
43	String toUpperCase()
使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
44	String toUpperCase(Locale locale)
使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
45	String trim()
返回字符串的副本,忽略前导空白和尾部空白。
46	static String valueOf(primitive data type x)
返回给定data type类型x参数的字符串表示形式。
47	contains(CharSequence chars)
判断是否包含指定的字符系列。
48	isEmpty()
判断字符串是否为空。

三、类StringBuffer

与String的区别:

类 String:字符串对象一旦创建,其内容不能再被修改。
类 StringBuffer:字符串创建完仍可以修改字符串内容。

介绍

字符串缓冲区机制:预先申请一个缓冲区存放字符序列,当长度超过缓冲区大小,则改变大小容纳更多字符。
一定程度上避免改变字符串缓冲区长度时频繁申请内存。
缓冲区大小,也称字符串缓冲区的容量
缓冲区的字符序列中所包含的字符个数,也称为字符串缓冲区的长度

构造

StringBuffer b = new StringBuffer("hello");

来源菜鸟教程
在这里插入图片描述

方法

方法 length()
返回 StringBuffer 的长度
方法 capacity()
返回StringBuffer 的容量
方法 setLength(int newLength) 
设置StringBuffer 的长度
方法 trimToSize() 
减少 StringBuffer 的存储空间,使得减少 StringBuffer 的容量与StringBuffer的长度相等。

四、向量

向量概念

预先给向量对象分配一定的存储空间,然后再给向量对象添加元素或设置元素值。

介绍

1.向量对象的存储空间大小称为向量对象的容量,其单位是元素个数。
2.向量对象的实际元素个数,称为向量对象的长度。
3.如果向量对象的长度发生变化,当新长度超过在长度变化之前的向量对象旧容量时,向量对象的容量会自动扩大

创建

Vector<String>  vs = new Vector<String>();  //创建元素类型为字符串的向量对象

Vector<Object> vo = new Vector<Object>();   //创建元素类型为Object的向量对象
Vector v = new Vector();

向量实例对象操作

在这里插入图片描述

向量添加元素

在这里插入图片描述

import java.util.Vector;

class Main {
    public static void main(String[] args) {
        Vector<String> mammals= new Vector<>();

        //使用add()方法
        mammals.add("Dog");
        mammals.add("Horse");

        //使用索引号
        mammals.add(2, "Cat");
        System.out.println("Vector: " + mammals);

        // 使用 addAll() 方法
        Vector<String> animals = new Vector<>();
        animals.add("Crocodile");

        animals.addAll(mammals);
        System.out.println("New Vector: " + animals);
    }
}

向量访问元素

在这里插入图片描述

import java.util.Iterator;
import java.util.Vector;

class Main {
    public static void main(String[] args) {
        Vector<String> animals= new Vector<>();
        animals.add("Dog");
        animals.add("Horse");
        animals.add("Cat");

        // 使用 get() 方法
        String element = animals.get(2);
        System.out.println("Element at index 2: " + element);

        // 使用 iterator()
        Iterator<String> iterate = animals.iterator();
        System.out.print("Vector: ");
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

向量删除元素

在这里插入图片描述

import java.util.Vector;

class Main {
    public static void main(String[] args) {
        Vector<String> animals= new Vector<>();
        animals.add("Dog");
        animals.add("Horse");
        animals.add("Cat");

        System.out.println("Initial Vector: " + animals);

        //使用 remove() 方法
        String element = animals.remove(1);
        System.out.println("Removed Element: " + element);
        System.out.println("New Vector: " + animals);

        // 使用 clear() 方法
        animals.clear();
        System.out.println("Vector after clear(): " + animals);
    }
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值