【笔记】Java的字符串

前言

Java的字符串学习笔记

声明字符串

1
String str;

定义字符串

创建字符串对象

1
String str = new String("文本内容");

通过字面量定义字符串

1
String str = "文本内容";

字符串的缓存机制

  • 通过字面量创建的字符串对象,会从字符串缓存池中寻找相同字符串对象
1
2
System.out.println("" == ""); // true
System.out.println(new String("") == new String("")); // false

字符串拼接

通过加法运算符

1
String result = "" + "";

通过实例方法

1
String result = "".concat("");

实例方法

获取指定下标的字符

1
char result = str.charAt(<num>);

转换大小写

所有字符转换为大写

1
String result = str.toUpperCase();

所有字符转换为小写

1
String result = str.toLowerCase();

查找子字符串所在位置

<str>:需要查找的字符串
<num>:下标数

查找第一次出现指定子字符串的位置

1
int result = str.indexOf(<str>);
从指定位置查找
1
int result = str.indexOf(<str>, <num>);

查找最后一次出现指定子字符串的位置

1
int result = str.lastIndexOf(<str>);

判断开头结尾

判断开头

1
boolean result = str.startsWith(<str>);

判断结尾

1
boolean result = str.endsWith(<str>);

判断是否包含子字符串

1
boolean result = str.contains(<str>);

替换子字符串

<str_old>:替换前的子字符串
<str_new>:替换后的子字符串

1
String result = str.replace("<str_old>", "<str_new>");

字符串截取

<num_start>:起始位置
<num_end>:截止位置

通过指定下标截取

1
String result = str.substring(<num_start>, <num_end>);

从指定位置开始到末尾

1
String result = str.substring(<num_start>);

去除首位空白字符

  • 去除Ascii码中定义的空白字符
1
String result = str.trim();

转换为字符数组

1
char[] result = str.toCharArray();

转换为字节数组

1
byte[] result = str.getBytes();

正则表达式

<reg>:正则表达式

字符串验证

1
boolean result = str.matches(<reg>);

字符串分割

1
String[] result = str.split(<reg>);

指定字符串替换

1
String result = str.replaceAll(<reg>, <str>);

字符串比较

1
boolean result = str.equals(str);

不区分大小写

1
boolean result = str.equalsIgnoreCase(str);

类方法

将其他类型转换为字符串

<other>:其他类型的值

1
String result = String.valueOf(<other>);

完成

参考文献

菜鸟笔记