跳到主要内容

Java 字符串

字符串变量是 Java 中的引用类型,用来表示一串字符序列,可以是任意长度的字符序列。

字符串变量可以用两种方式创建:

  • 使用双引号定义:String str = "Hello World";
  • 使用构造函数创建:String str = new String("Hello World");(字符串变量也可以用 + 运算符来连接字符串,类似于 JS)
  • 可以使用 String 类提供的一系列操作函数,来对字符串进行一系列操作

示例:

String str1 = "Hello";
String str2 = "World";
String str3 = str1 + str2; // str3 = "Hello World"

String str = "Hello World";
// 检索子串
str.indexOf("World"); // 返回6
// 替换子串
str.replace("Hello", "Hi"); // 返回"Hi World"
// 分割字符串
str.split(" "); // 返回["Hello", "World"]

常用字符串函数

  • 返回此字符串的长度 int length()
  • 获取指定位置的字符 char charAt(int index)
  • 截取子串 String substring(int beginIndex)
  • 转换大小写 String toUpperCase()
  • 查找子串 int indexOf(int ch)
  • 检查字符串开头 boolean startsWith(String prefix)
  • 检查字符串结尾 boolean endsWith(String suffix)
  • 去除字符串头尾空格 String trim()
  • 比较两个字符串 boolean equals(Object anObject)

示例:

String str = "Hello World";

str.length(); // 返回11
str.charAt(0); // 返回'H'
str.substring(0, 5); // 返回"Hello"
str.toUpperCase(); // 返回"HELLO WORLD"
str.indexOf("World"); // 返回6
str.startsWith("Hello"); // 返回true
str.endsWith("World"); // 返回true
str.trim(); // 返回"Hello World"
str.equals("Hello World"); // 返回true

equal== 区别:

equal== 的主要区别在于,equal 方法比较的是两个字符串的内容是否相等,而 == 则是比较两个字符串是否是同一个对象。

所以一般使用 equal

示例:

String str1 = "Hello World";
String str2 = new String("Hello World");

// 使用equal方法
System.out.println(str1.equals(str2)); //true

// 使用==操作符
System.out.println(str1 == str2); //false