一、什麼是String數組
String數組是一種用來存儲字元串類型數據的數據結構,它能夠存儲多個字元串並且能夠按照一定的邏輯順序訪問其中的元素。
String數組是一種固定長度、可變內容的數據結構,長度不可變,但是可以通過改變數組中的元素來改變其內容。
下面是一個創建String數組的例子:
String[] names = {"John", "Mary", "Tom", "Mike"};
二、常見操作
1. 獲取數組長度
通過調用數組的length屬性可以獲得數組的長度,如下所示:
String[] names = {"John", "Mary", "Tom", "Mike"};
System.out.println(names.length);
// 輸出:4
2. 遍曆數組
通過for循環可以遍曆數組中的所有元素:
String[] names = {"John", "Mary", "Tom", "Mike"};
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
// 輸出:
// John
// Mary
// Tom
// Mike
另外,也可以使用增強型for循環遍曆數組:
String[] names = {"John", "Mary", "Tom", "Mike"};
for (String name : names) {
System.out.println(name);
}
// 輸出:
// John
// Mary
// Tom
// Mike
3. 數組元素的讀取和修改
通過下標可以讀取數組中的元素,下標從0開始:
String[] names = {"John", "Mary", "Tom", "Mike"};
System.out.println(names[0]); // 輸出:John
System.out.println(names[2]); // 輸出:Tom
通過下標可以修改數組中的元素:
String[] names = {"John", "Mary", "Tom", "Mike"};
names[1] = "Kate";
System.out.println(names[1]); // 輸出:Kate
三、示例代碼
下面是一個使用String數組存儲學生信息的示例代碼:
public class Student {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
public static void main(String[] args) {
Student[] students = new Student[]{
new Student("John", 20, "male"),
new Student("Mary", 21, "female"),
new Student("Tom", 19, "male"),
new Student("Mike", 22, "male")
};
for (Student student : students) {
System.out.println(student);
}
}
}
輸出結果為:
Student{name='John', age=20, gender='male'}
Student{name='Mary', age=21, gender='female'}
Student{name='Tom', age=19, gender='male'}
Student{name='Mike', age=22, gender='male'}
四、總結
String數組是一種常見的數據結構,可以用來存儲字元串類型的數據。它擁有固定長度、可變內容的特點,提供了多種常見的操作方式。掌握了String數組的操作,可以方便地處理很多實際問題。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/241914.html
微信掃一掃
支付寶掃一掃