java学习记录第八周

在Java中,字符串是通过`String`类来表示的,`String`类是不可变的,这意味着一旦一个字符串被创建,它的值就不能被改变。
  1. 字符串的创建
    字符串可以通过以下两种方式创建:

使用字符串字面量:

  String str1 = "Hello";

使用new关键字:

  String str2 = new String("Hello");

使用字符串字面量创建的字符串会存储在字符串常量池中,而使用new关键字创建的字符串则会存储在堆中。
2. 字符串的比较

使用==比较字符串的引用是否相等。

使用equals()方法比较字符串的内容是否相等。

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

  System.out.println(str1 == str2); // true
  System.out.println(str1 == str3); // false
  System.out.println(str1.equals(str3)); // true
  1. 字符串的拼接

字符串拼接可以使用+操作符或StringBuilder类:
-使用+操作符:

  String str = "Hello" + " " + "World";

-使用StringBuilder类:

  StringBuilder sb = new StringBuilder();
  sb.append("Hello");
  sb.append(" ");
  sb.append("World");
  String str = sb.toString();

在循环中拼接字符串时,使用StringBuilder比使用+操作符更高效。
4. 字符串的分割

使用split()方法可以将字符串按照指定的分隔符分割成字符串数组:

String str = "Hello,World,Java";
String[] arr = str.split(",");
for (String s : arr) {
  System.out.println(s);
}
  1. 字符串的查找和替换

使用indexOf()lastIndexOf()方法查找子字符串的位置。
使用replace()replaceAll()方法替换子字符串。

  String str = "Hello World";
  int index = str.indexOf("World");
  System.out.println(index); // 6

  String replaced = str.replace("World", "Java");
  System.out.println(replaced); // Hello Java
  1. 字符串的截取

使用substring()方法截取字符串:

String str = "Hello World";
String sub = str.substring(6);
System.out.println(sub); // World
  1. 字符串的大小写转换

使用toUpperCase()toLowerCase()方法转换字符串的大小写:

String str = "Hello World";
String upper = str.toUpperCase();
String lower = str.toLowerCase();
System.out.println(upper); // HELLO WORLD
System.out.println(lower); // hello world
  1. 字符串的格式化

使用String.format()方法格式化字符串:

int num = 10;
String str = String.format("The number is %d", num);
System.out.println(str); // The number is 10
  1. 字符串的长度

使用length()方法获取字符串的长度:

String str = "Hello";
System.out.println(str.length()); // 5
posted @ 2024-08-21 12:01  呓语-MSHK  阅读(22)  评论(0)    收藏  举报