Java 字符串取值:全面指南163
在 Java 中,字符串是不可变的字符序列,广泛用于存储文本数据。提取字符串的特定部分对于各种编程任务至关重要,例如文本处理、数据验证和字符串操作。
charAt(int index)
charAt(index) 方法返回指定索引处的字符。索引从 0 开始,表示字符串的第一个字符。如果索引超出范围,则抛出 IndexOutOfBoundsException。String str = "Hello";
char c = (0); // 取出第一个字符,即 'H'
substring(int startIndex, int endIndex)
substring(startIndex, endIndex) 方法返回从指定开始索引到指定结束索引之间的子字符串。结束索引不包括在结果中。如果起始索引或结束索引超出范围,则抛出 IndexOutOfBoundsException。String str = "Hello World";
String substring = (0, 5); // 取出 "Hello" 子字符串
substring(int startIndex)
substring(startIndex) 方法返回从指定起始索引到字符串结尾的子字符串。如果起始索引超出范围,则抛出 IndexOutOfBoundsException。String str = "Hello World";
String substring = (6); // 取出 "World" 子字符串
indexOf(char ch)
indexOf(ch) 方法返回字符 ch 在字符串中的第一个出现位置。如果没有找到该字符,则返回 -1。String str = "Hello World";
int index = ('o'); // 取出字符 'o' 的索引,即 4
lastIndexOf(char ch)
lastIndexOf(ch) 方法返回字符 ch 在字符串中的最后一个出现位置。如果没有找到该字符,则返回 -1。String str = "Hello World";
int index = ('l'); // 取出字符 'l' 的最后一个索引,即 9
contains(String str)
contains(str) 方法检查字符串是否包含指定的子字符串 str。如果包含,则返回 true,否则返回 false。String str = "Hello World";
boolean contains = ("World"); // true
startWith(String prefix)
startWith(prefix) 方法检查字符串是否以指定的子字符串 prefix 开头。如果开头,则返回 true,否则返回 false。String str = "Hello World";
boolean startsWith = ("Hello"); // true
endsWith(String suffix)
endsWith(suffix) 方法检查字符串是否以指定的子字符串 suffix 结尾。如果结尾,则返回 true,否则返回 false。String str = "Hello World";
boolean endsWith = ("World"); // true
repeat(int n)
repeat(n) 方法返回该字符串重复 n 次的新字符串。如果 n 小于 0,则抛出 IllegalArgumentException。String str = "Hello";
String repeated = (3); // "HelloHelloHello"
replace(CharSequence target, CharSequence replacement)
replace(target, replacement) 方法返回一个新字符串,其中所有出现的指定目标序列 target 都用指定的替换序列 replacement 替换。target 和 replacement 可以是字符串或正则表达式。String str = "Hello World";
String replaced = ("World", "Universe"); // "Hello Universe"
toLowerCase()
toLowerCase() 方法返回一个新字符串,其中所有字符都转换为小写。原始字符串保持不变。String str = "Hello World";
String lowercase = (); // "hello world"
toUpperCase()
toUpperCase() 方法返回一个新字符串,其中所有字符都转换为大写。原始字符串保持不变。String str = "hello world";
String uppercase = (); // "HELLO WORLD"
trim()
trim() 方法返回一个新字符串,其中删除了字符串开头和结尾的所有空白字符。原始字符串保持不变。String str = " Hello World ";
String trimmed = (); // "Hello World"
2024-10-17
下一篇:Java 数据库项目:从零到部署
PHP正确获取MySQL中文数据:从乱码到清晰的完整指南
https://www.shuihudhg.cn/132249.html
Java集合到数组:深度解析转换机制、类型安全与性能优化
https://www.shuihudhg.cn/132248.html
现代Java代码简化艺术:告别冗余,拥抱优雅与高效
https://www.shuihudhg.cn/132247.html
Python文件读写性能深度优化:从原理到实践
https://www.shuihudhg.cn/132246.html
Python文件传输性能优化:深入解析耗时瓶颈与高效策略
https://www.shuihudhg.cn/132245.html
热门文章
Java中数组赋值的全面指南
https://www.shuihudhg.cn/207.html
JavaScript 与 Java:二者有何异同?
https://www.shuihudhg.cn/6764.html
判断 Java 字符串中是否包含特定子字符串
https://www.shuihudhg.cn/3551.html
Java 字符串的切割:分而治之
https://www.shuihudhg.cn/6220.html
Java 输入代码:全面指南
https://www.shuihudhg.cn/1064.html