這次是完成一些小任務來試試身手,免得生疏:
編寫程序,使用charAt和length方法,將字符串"HelloWorld"拆分為"Hello"和"World"兩個子串并輸出。
設計一個方法,利用indexOf和lastlndexOf,查找字符串中某個字符最后一次出現的位置,若不存在則返回-1。
使用substring方法,截取郵箱地址(如"user@example.com")中的用戶名部分(即"@"之前的內容)。編寫程序,通過startsWith和endsWith方法判斷一個文件名稱(如"document.txt")是否是文本文件(以".txt"結尾)。
利用toLowerCase和toUpperCase方法,將字符串"AbCdEfG"轉換為全小寫和全大寫兩種形式并輸出。
設計方法,使用trim和isEmpty處理用戶輸入的字符串,去除首尾空格后判斷是否為空字符串。
使用replace(或replaceAll方法,將字符串中的所有數字字符替換為"",例如"a1b2c3"轉換為"abc"。編寫程序,通過split方法將CSV格式字符串(如"張三,20,男")拆分為數組并分別輸出各元素。
利用equals和equalslgnoreCase比較兩個字符串是否相等,區分大小寫和不區分大小寫兩種情況。
設計一個方法,結合contains和substring,判斷字符串是否包含指定子串,若包含則返回該子串首次出現的完整前后內容
任務一:Test01 字符串基礎操作
1. 拆分字符串(test_a)
public void test_a(){String hello = str.substring(0, 5);String world = str.substring(5);System.out.println("拆分結果:"+hello+"和"+world);
}
執行結果:
拆分結果:Hello和World
關鍵點解析:
substring(0, 5)
:截取索引0到4的字符(不包括索引5)substring(5)
:從索引5開始截取到字符串末尾- 索引位置:H(0), e(1), l(2), l(3), o(4), W(5), o(6), r(7), l(8), d(9)
2. 查找字符最后位置(test_b)
public void test_b(){System.out.println("查找的隨機字母是" + randomString);System.out.println(randomString+"最后出現位置: " + lastCharPosition("HelloWorld", randomString));
}public static int lastCharPosition(String s, String c) {if (s.indexOf(c) == -1) {return -1;}else {return s.lastIndexOf(c);}
}
執行結果示例:
查找的隨機字母是o
o最后出現位置: 6
關鍵點解析:
indexOf()
:檢查字符是否存在lastIndexOf()
:返回字符最后出現的位置- 返回-1表示字符不存在
3. 提取郵箱用戶名(test_c)
public void test_c(){int atIndex = email.indexOf('@');if (atIndex != -1) {System.out.println("用戶名: " + email.substring(0, atIndex));}
}
執行結果:
用戶名: user
關鍵點解析:
indexOf('@')
:查找@符號的位置substring(0, atIndex)
:截取從0到@符號前的字符串
任務二:Test02 字符串高級操作
1. 判斷文本文件(test_a)
public void test_a() {if (fileName.toLowerCase().startsWith("document") && fileName.toLowerCase().endsWith(".txt")) {System.out.println(fileName + " 是一個文本文件。");} else {System.out.println(fileName + " 不是一個文本文件。");}
}
執行結果:
document.txt 是一個文本文件。
關鍵點解析:
startsWith()
:檢查字符串開頭endsWith()
:檢查字符串結尾toLowerCase()
:統一大小寫處理
2. 大小寫轉換(test_b)
public void test_b() {System.out.println("全小寫: " + str.toLowerCase());System.out.println("全大寫: " + str.toUpperCase());
}
執行結果:
全小寫: abcdefg
全大寫: ABCDEFG
3. 處理用戶輸入(test_c)
public void test_c() {System.out.print("請輸入字符串: ");String userInput = scanner.nextLine();String trimmedInput = userInput.trim();if (trimmedInput.isEmpty()) {System.out.println("去除首尾空格后字符串為空。");} else {System.out.println("去除首尾空格后的字符串為: \"" + trimmedInput + "\"");}
}
執行結果示例:
請輸入字符串: Hello World
去除首尾空格后的字符串為: "Hello World"
4. 替換數字字符(test_d)
public void test_d() {String replacedString = numberString.replaceAll("\\d", "");System.out.println("替換數字后的字符串為: " + replacedString);
}
執行結果:
替換數字后的字符串為: abc
關鍵點解析:
replaceAll("\\d", "")
:正則表達式匹配所有數字并替換為空\\d
:正則表達式匹配數字字符
任務三:Test03 字符串應用實踐
1. 拆分CSV數據(test_a)
public void test_a(){String csvString = "張三,20,男";String[] elements = csvString.split(",");for (String element : elements) {System.out.println(element);}
}
執行結果:
張三
20
男
關鍵點解析:
split(",")
:使用中文逗號作為分隔符- 返回字符串數組
2. 字符串比較(test_b)
public void test_b(){String str1 = "Hello";String str2 = "hello";System.out.println("str1 等于 str2 (區分大小寫): " + str1.equals(str2));System.out.println("str1 等于 str2 (不區分大小寫): " + str1.equalsIgnoreCase(str2));
}
執行結果:
str1 等于 str2 (區分大小寫): false
str1 等于 str2 (不區分大小寫): true
3. 子串上下文提取(test_c)
public void test_c(){String text = "這是一個測試字符串,用于測試子串出現的完整前后內容。";String subString = "測試";String result = findSubstringWithContext(text, subString);System.out.println("包含子串的完整前后內容: " + result);
}public static String findSubstringWithContext(String text, String subString) {if (text.contains(subString)) {int startIndex = text.indexOf(subString);int endIndex = startIndex + subString.length();System.out.println("子串開始索引: " + startIndex);System.out.println("子串結束索引: " + endIndex);return text.substring(0, endIndex);}return "子串未找到";
}
執行結果:
子串開始索引: 3
子串結束索引: 5
包含子串的完整前后內容: 這是一個測試
關鍵點解析:
contains()
:檢查子串是否存在indexOf()
:獲取子串起始位置substring(0, endIndex)
:截取從開始到子串結束的內容
contains 和 substring 方法深度解析
1. contains 方法詳解
方法簽名:
public boolean contains(CharSequence s)
工作原理:
- 檢查字符串是否包含指定字符序列
- 底層調用
indexOf()
方法 - 返回
true
如果找到子串,否則false
使用示例:
String str = "Hello World";
System.out.println(str.contains("World")); // true
System.out.println(str.contains("world")); // false (大小寫敏感)
2. substring 方法詳解
方法簽名:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
參數說明:
beginIndex
:起始索引(包含)endIndex
:結束索引(不包含)
使用示例:
String str = "HelloWorld";
System.out.println(str.substring(5)); // "World"
System.out.println(str.substring(0, 5)); // "Hello"
3. contains 和 substring 結合使用
優化后的子串上下文提取方法:
public static String getSubstringContext(String text, String sub) {if (!text.contains(sub)) {return "未找到子串";}int start = text.indexOf(sub);int end = start + sub.length();String before = (start > 0) ? text.substring(0, start) : "";String after = (end < text.length()) ? text.substring(end) : "";return "前文: \"" + before + "\", 子串: \"" + sub + "\", 后文: \"" + after + "\"";
}
測試結果:
String text = "這是一個測試字符串,用于測試子串出現的完整前后內容。";
String subString = "測試";
System.out.println(getSubstringContext(text, subString));
輸出:
前文: "這是一個", 子串: "測試", 后文: "字符串,用于測試子串出現的完整前后內容。"
完整代碼整合
public class StringOperationsTutorial {public static void main(String[] args) {// 任務一:基礎操作testTask1();// 任務二:高級操作testTask2();// 任務三:應用實踐testTask3();}// 任務一實現public static void testTask1() {System.out.println("===== 任務一:字符串基礎操作 =====");// 1. 拆分字符串String str = "HelloWorld";String hello = str.substring(0, 5);String world = str.substring(5);System.out.println("拆分結果: " + hello + " 和 " + world);// 2. 查找字符最后位置char searchChar = 'o';int lastPos = lastCharPosition(str, searchChar);System.out.println("字符 '" + searchChar + "' 最后出現位置: " + lastPos);// 3. 提取郵箱用戶名String email = "user@example.com";int atIndex = email.indexOf('@');if (atIndex != -1) {System.out.println("郵箱用戶名: " + email.substring(0, atIndex));}}public static int lastCharPosition(String s, char c) {return s.lastIndexOf(c);}// 任務二實現public static void testTask2() {System.out.println("\n===== 任務二:字符串高級操作 =====");// 1. 判斷文本文件String fileName = "document.txt";if (fileName.endsWith(".txt")) {System.out.println(fileName + " 是文本文件");} else {System.out.println(fileName + " 不是文本文件");}// 2. 大小寫轉換String mixedCase = "AbCdEfG";System.out.println("全小寫: " + mixedCase.toLowerCase());System.out.println("全大寫: " + mixedCase.toUpperCase());// 3. 處理用戶輸入String userInput = " Hello World ";String trimmed = userInput.trim();System.out.println("原始輸入: '" + userInput + "'");System.out.println("去除空格: '" + trimmed + "'");System.out.println("是否為空: " + trimmed.isEmpty());// 4. 替換數字字符String withNumbers = "a1b2c3";String withoutNumbers = withNumbers.replaceAll("\\d", "");System.out.println("替換數字: " + withoutNumbers);}// 任務三實現public static void testTask3() {System.out.println("\n===== 任務三:字符串應用實踐 =====");// 1. 拆分CSV數據String csv = "張三,20,男";String[] parts = csv.split(",");System.out.println("CSV拆分結果:");for (String part : parts) {System.out.println(part);}// 2. 字符串比較String str1 = "Java";String str2 = "java";System.out.println("區分大小寫比較: " + str1.equals(str2));System.out.println("不區分大小寫比較: " + str1.equalsIgnoreCase(str2));// 3. 子串上下文提取String text = "Java編程很有趣,Java是最好的編程語言之一";String sub = "Java";String context = getSubstringContext(text, sub);System.out.println("子串上下文: " + context);}public static String getSubstringContext(String text, String sub) {if (!text.contains(sub)) {return "未找到子串: \"" + sub + "\"";}int start = text.indexOf(sub);int end = start + sub.length();String before = (start > 0) ? text.substring(0, start) : "[開頭]";String after = (end < text.length()) ? text.substring(end) : "[結尾]";return "前文: \"" + before + "\", 子串: \"" + sub + "\", 后文: \"" + after + "\"";}
}
執行結果預覽
===== 任務一:字符串基礎操作 =====
拆分結果: Hello 和 World
字符 'o' 最后出現位置: 6
郵箱用戶名: user===== 任務二:字符串高級操作 =====
document.txt 是文本文件
全小寫: abcdefg
全大寫: ABCDEFG
原始輸入: ' Hello World '
去除空格: 'Hello World'
是否為空: false
替換數字: abc===== 任務三:字符串應用實踐 =====
CSV拆分結果:
張三
20
男
區分大小寫比較: false
不區分大小寫比較: true
子串上下文: 前文: "", 子串: "Java", 后文: "編程很有趣,Java是最好的編程語言之一"
關鍵知識點總結
- 字符串基礎操作:
- 使用
substring()
進行字符串分割 - 使用
indexOf()
和lastIndexOf()
查找字符位置 - 郵箱用戶名提取技巧
- 使用
- 字符串高級操作:
- 文件類型判斷(
endsWith()
) - 大小寫轉換(
toLowerCase()
,toUpperCase()
) - 用戶輸入處理(
trim()
,isEmpty()
) - 正則表達式替換(
replaceAll()
)
- 文件類型判斷(
- 字符串應用實踐:
- CSV數據解析(
split()
) - 字符串比較(
equals()
,equalsIgnoreCase()
) - 子串上下文提取(
contains()
,indexOf()
,substring()
)
- CSV數據解析(
- contains 和 substring 深度應用:
- 檢查子串存在性
- 定位子串位置
- 提取前后文內容
- 處理邊界情況(開頭、結尾)