Common methods of Java String

string lookup

Two methods for finding strings, indexOf(String s) and lastIndexOf(String s).

String str = "tyson-json";
int index = str.indexOf("son");//返回指定字符串首次出现的索引位置,若找不到指定字符串,则返回-1
int index = str.lastIndexOf("son");//返回指定字符串最后一次出现的索引位置,若找不到指定字符串,则返回-1

Get the character at the specified index position

Use chatAt(int index) to return the character at the specified index position

String str = "tyson";
char c = str.charAt(2);

get substring

Use the substring() method to intercept strings

String str = "hello world";
String str1=str.substring(6);//从指定位置开始截取到字符串末尾
String str2=str.substring(0,6);//beginIndex,endIndex

String split

Use the split() method to split the content of the string according to the specified split character or string, and the split result is stored in the string array

String str = "Hello world";
String[] strArray = str.split(" ");//按空格分割,分割后结果放在数组strArray

replace string

replace(oldChar,newChar)方法

String str = "hello world";
String str1 = str.replace('h','H');

Determine the start and end of a string

The startsWith() method and the endsWith() method are used to determine whether the string starts or ends with the specified content, respectively. The return value of both methods is of type boolean

String str = "hello";
Boolean isStart = str.startsWith("h");//true
Boolean isEnd = str.endsWith("h");//false

Check if strings are equal

equals() method is case sensitive, equalsIgnoreCase() is insensitive

String str  = "Hello";
Boolean isEqual = str.equals("hello");//false
Boolean isEqualsIgnoreCase = str.equalsIgnoreCase("hello");//true

letter case conversion

String str = "Hello world";
String str1 = str.toLowerCase();//转化成小写字母
String str2 = str.toUpperCase();//转化成大写字母

remove spaces

The trim() method removes spaces at the beginning or end of a string

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324645405&siteId=291194637