Home  >  Article  >  Java  >  What are the usage methods of String class in Java?

What are the usage methods of String class in Java?

WBOY
WBOYforward
2023-05-16 15:33:481148browse

String

String class:

represents a string and provides common string processing methods in development, such as: finding the length of a string, intercepting a string, and replacing a string In other methods, the string is a constant, and its value cannot be modified after it is created.

First of all, let’s check the official documents to see what methods the official has set for the String class: String also belongs to the java.lang package, so there is no need to import it. It is partially displayed here. You can refer to the full content:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html

What are the usage methods of String class in Java?

Several commonly used methods:

charAt(int index):

Pass in the character subscript, intercept the character, and the return value is char type:

String str = "hello world";
        char a = str.charAt(0);
        System.out.println(a);

//Output: h

compareTo(String anotherString): Compare the two strings to first match the character corresponding to the subscript that is different, return the difference in ASCII code, do not ignore case , return String type:

String str = "hello world";
int a = str.compareTo("Aello world");
System.out.println(a);

//Compare h and A, output 39

compareToIgnoreCase(String str): Compare two strings in dictionary order, ignoring the size Write, return String type:

String str = "hello world";
int a = str.compareToIgnoreCase("Aello world");
System.out.println(a);

//Compare h and A, output 7

concat(String str): Concatenate string:

String str = "hello world";
String a = str.concat("abc");
System.out.println(a);

//Output: hello worldabc

This method is used to find whether a certain string is included in the target string and returns a Boolean value:

String str = "hello world";
boolean a = str.contains("e"); //传入需要判断的值
 System.out.println(a)

//Output: true

boolean a = str.contains("a");  //判断a
System.out.println(a);

//Output false

endsWith(String suffix): Determine whether it ends with the specified one (can be judged by the user's email suffix) Return Boolean value:

String str = "1234567489@qq.com";
boolean a = str.endsWith("@qq.com");  //需要判断的内容
System.out.println(a);

//Output: true

startsWith(String prefix): Determine whether the string starts with the specified prefix: (URL judgment) Return Boolean Value:

String str = "www.baidu.com";
boolean a = str.startsWith("www");
System.out.println(a);

//Output: true

equals(Object anObject): Compares the string with the specified string for equality, case-sensitive, returns Boolean Value:

String str = "www.baidu.com";
boolean a = str.equals("Www.baidu.com");  //第一个w改为大写W
System.out.println(a);

//Output: false
//If the two are the same, output true

equalsIgnoreCase(String anotherString): Convert the string to the specified Whether string comparison is equal, case-insensitive, returns Boolean value:

String str = "www.baidu.com";
boolean a = str.equalsIgnoreCase("Www.Baidu.com");  //第一个w改为大写W
System.out.println(a);
//不区分大小写后,即使一个或多个字符改为大写,也不影响判断

//Output true

indexOf(String str): Returns the index in the string The index of the specified value is found once, and the int type is returned:

String str = "www.baidu.com";
int a = str.indexOf("a");  //判断a
System.out.println(a);

//Output: 5

lastIndexOf(String str): Returns the last time found in the string Index of the specified value, return int type:

String str = "www.baidu.com";
int a = str.indexOf("a");  //判断a,因为这个字符串只有一个a,所以还是5
System.out.println(a);

//Output: 5

length(): Returns the string length, int type:

String str = "www.baidu.com";
int a = str.length();
System.out.println(a);

//Output: 13

toLowerCase(): Convert the string into lowercase letters. If it is originally lowercase, it will not change and return String type:

String str = "www.BAIDU.com";
String a = str.toLowerCase();
System.out.println(a);

//Output: www.baidu.com

toUpperCase(): Convert the string to uppercase letters:

String str = "www.BAIDU.com";
String a = str.toLowerCase();
System.out.println(a);

//Output: WWW. BAIDU.COM

trim(): Remove the blanks at both ends of the string:

String str = "       www.baidu.com     ";   //在前后端输出多个空格
String a = str.trim();
System.out.println(a);

//Output: www.baidu.com

String substring(int beginIndex,int endIndex): Intercept string (index includes beginIndex, does not include endIndex):

String str = "www.baidu.com";
String a = str.substring(0,6);  //截取下标0开始,6结束(不包含下标为6的字符)
System.out.println(a);

//Output: www.ba

There are many methods of String, so I won’t list them all here. You can refer to the official website documentation to use them.

The length of a string object cannot be changed, and its content cannot be modified or appended. character. In fact, sometimes this cannot meet business needs, and there are always times when the string needs to be changed, so Java provides two types of variable string string buffers, StringBuffer and StringBuilder.

StringBuffer and StringBuilder:

First look at the official introduction:

What are the usage methods of String class in Java?

Simply put, StringBuffer is a variable sequence of characters, the length of the column and content can be changed by calling certain methods. Some StringBuffer methods are as follows. For details, please refer to:

https://docs.oracle.com/en/java/javase/17/docs/api/java .base/java/lang/StringBuffer.html

What are the usage methods of String class in Java?

Officially uses an overloaded form for the append method to meet the needs of different business logic. To use StringBuffer, you must first create an object, because it is a class

public class StringBuffertest {
    public static void main(String[] args) {

        String str = "hello world";
        StringBuffer s = new StringBuffer(str);  //创建StringBuffer类,这个和普通类创建方法是一样的
        s.append("hello world");    //使用StringBuffer的append方法
        System.out.println(s);
    }
}

//Output: hello worldhello world
//This completes the modification of the string

StringBuilder The usage is the same:

String str = "hello world";
StringBuilder s = new StringBuilder(str);

So what is the difference between String, StringBuilder and StringBuffer?

  • Variability: String is an immutable character sequence, Builder and Buffer are variable character sequences

  • 安全性:String是线程安全的,StringBuilder是线程不安全的,StringBuffer是线程安全。StringBuidler效率高于StringBuffer。因为String是不可变的一般情况下,效率最低。

  • 使用场景:如果字符串创建后基本上不需要更改,使用String类型,如果需要更改操作较多使用StringBuilder,如果要求线程安全使用StringBuffer。

StringBuffer和StringBuilder类的好处:

对象能够被多次的修改,并且不产生新的未使用对象

String类总结:

String有哪些特性:

  • 不变性:String 是只读字符串,是一个典型的 immutable 对象,对它进行任何操作,其实都是创 建一个新的对象,再把引用指向该对象。不变模式的主要作用是确保在对象需要被多个线程频繁访问和共享时,数据的一致性不会被破坏。

  • 常量池优化:String 对象创建之后,会在字符串常量池中进行缓存,如果下次创建同样的对象时, 会直接返回缓存的引用。

  • final:使用 final 来定义 String 类,表示 String 类不能被继承,提高了系统的安全性。

小扩展:什么是字符串常量池?

字符串常量池位于堆内存中,专门用来存储字符串常量,可以提高内存的使用率,避免开辟多块空间存储相同的字符串,在创建字符串时 JVM 会首先检查字符串常量池,如果该字符串已经存在池中,则返回它的引用,如果不存在,则实例化一个字符串放到池中,并返回其引用。

字符型常量(char)和字符串常量(String)的区别:

  • 形式上:字符常量是单引号引起的一个字符 字符串常量是双引号引起的若干个字符

  • 含义上:字符常量相当于一个整形值(ASCII值),可以参加表达式运算,字符串常量代表一个地址值(该字符串在内存中存放位置)

  • 占内存大小:字符常量只占一个字节 字符串常量占若干个字节(至少一个字符结束标志)

特别注意: 我们知道数组也有 length(),用来判断该数组长度:

int [] a = {1,2,3,4,5};
system.out.println(a.length);

//输出:5

但是千万要注意:

数组中length()是属性,String中length()是方法!! 数组中length()是属性,String中length()是方法!! 数组中length()是属性,String中length()是方法!!

The above is the detailed content of What are the usage methods of String class in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete