Java String 类用法详解 - 存储、操作文本数据
String 是一种数据类型,用于表示一串字符。它可以被用于存储和操作文本数据。以下是 String 的一些常见用法:
-
创建 String 对象: String str = 'Hello World'; // 通过字符串字面量创建 String 对象 String str = new String('Hello World'); // 通过构造函数创建 String 对象
-
获取字符串长度: int length = str.length(); // 返回字符串的字符个数
-
字符串连接: String str1 = 'Hello '; String str2 = 'World'; String result = str1 + str2; // 结果为'Hello World'
-
字符串比较: String str1 = 'Hello'; String str2 = 'Hello'; boolean isEqual = str1.equals(str2); // 比较两个字符串是否相等
-
字符串查找: String str = 'Hello World'; int index = str.indexOf('World'); // 返回子串'World'在字符串中的起始索引
-
字符串截取: String str = 'Hello World'; String subStr = str.substring(6); // 返回子串'World'
-
字符串分割: String str = 'Hello,World'; String[] parts = str.split(','); // 返回分割后的子串数组['Hello', 'World']
-
字符串替换: String str = 'Hello World'; String newStr = str.replace('World', 'Java'); // 返回替换后的新字符串'Hello Java'
-
字符串大小写转换: String str = 'Hello World'; String upperCase = str.toUpperCase(); // 返回全大写字符串'HELLO WORLD' String lowerCase = str.toLowerCase(); // 返回全小写字符串'hello world'
这些只是 String 的一些基本用法,String 类还提供了许多其他的方法来处理和操作字符串。
原文地址: https://www.cveoy.top/t/topic/o9uC 著作权归作者所有。请勿转载和采集!