search
HomeJavajavaTutorialHow to use java string?

How to use java string?

May 22, 2019 pm 01:21 PM
java string

How to use java string?

java String usage

String class is in the java.lang package, java uses the String class to create a character String variables, string variables belong to objects. Java declares the String class as a final class and cannot have subclasses. The String class object cannot be modified after it is created. It consists of 0 or more characters and is contained between a pair of double quotes. Let’s briefly familiarize yourself with its commonly used API

 java.lang.String  
 char charAt (int index)     返回index所指定的字符  
 String concat(String str)   将两字符串连接  
 boolean endsWith(String str)    测试字符串是否以str结尾  
 boolean equals(Object obj)  比较两对象  
 char[] getBytes     将字符串转换成字符数组返回  
 char[] getBytes(String str)     将指定的字符串转成制服数组返回  
 boolean startsWith(String str)  测试字符串是否以str开始  
 int length()    返回字符串的长度  
 String replace(char old ,char new)  将old用new替代  
 char[] toCharArray  将字符串转换成字符数组  
 String toLowerCase()    将字符串内的字符改写成小写  
 String toUpperCase()    将字符串内的字符改写成大写  
 String valueOf(Boolean b)   将布尔方法b的内容用字符串表示  
 String valueOf(char ch)     将字符ch的内容用字符串表示  
 String valueOf(int index)   将数字index的内容用字符串表示  
 String valueOf(long l)  将长整数字l的内容用字符串表示  
 String substring(int1,int2)     取出字符串内第int1位置到int2的字符串

1. Construction method

//直接初始化
String str = "abc";
//使用带参构造方法初始化
char[] char = {'a','b','c'};
String str1 = new String("abc");String str2 = new String(str);
String str3 = new String(char);

2. Find the length of the string and the character at a certain position

String str = new String("abcdef");
int strlength = str.length();//strlength = 7
char ch = str.charAt(4);//ch = e

3. Extract the substring

Use The substring method of the String class can extract the substring in the string. This method has two common parameters:

1) public String substring(int beginIndex)//This method starts from the beginIndex position and starts from the current string Remove the remaining characters and return them as a new string.

2) public String substring(int beginIndex, int endIndex)//This method starts from the beginIndex position, takes the characters from the current string to the endIndex-1 position and returns it as a new string.

String str1 = new String("abcdef");
String str2 = str1.substring(2);//str2 = "cdef"
String str3 = str1.substring(2,5);//str3 = "cde"

4. String comparison

1) public int compareTo(String anotherString)//This method compares the string contents in dictionary order. The returned integer value indicates the size relationship between the current string and the parameter string. If the current object is larger than the parameter, a positive integer is returned, otherwise a negative integer is returned, and 0 is returned if equal.

2) public int compareToIgnoreCase(String anotherString)//Similar to the compareTo method, but ignores case.

3) public boolean equals(Object anotherObject)//Compare the current string and the parameter string, return true when the two strings are equal, otherwise return false.

4) public boolean equalsIgnoreCase(String anotherString)//Similar to the equals method, but ignores case.

String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b = str1.compareToIgnoreCase(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d = str1.equalsIgnoreCase(str2);//d=true

5. String link

public String concat(String str)//将参数中的字符串str连接到当前字符串的后面,效果等价于"+"
String str = "aa".concat("bb").concat("cc");
//相当于String str = "aa"+"bb"+"cc";

6. Search for a single character in a string

1) public int indexOf (int ch/String str)//Used to find characters or substrings in the current string, return the position where the character or substring first appears from the left in the current string, or -1 if it does not appear.

2) public int indexOf(int ch/String str, int fromIndex)//The modified method is similar to the first one, the difference is that this method searches backward from the fromIndex position.

3) public int lastIndexOf(int ch/String str)//This method is similar to the first one, except that this method searches forward from the end of the string.

4) public int lastIndexOf(int ch/String str, int fromIndex)//This method is similar to the second method, except that this method searches forward from the fromIndex position.

String str = "I really miss you !";
int a = str.indexOf('a');//a = 4
int b = str.indexOf("really");//b = 2
int c = str.indexOf("gg",2);//c = -1
int d = str.lastIndexOf('s');//d = 6
int e = str.lastIndexOf('s',7);//e = 7

7. Case conversion

1) public String toLowerCase()//Returns a new string after converting all characters in the current string to lowercase

2) public String toUpperCase()//Returns a new string after converting all characters in the current string to uppercase

String str = new String("abCD");
String str1 = str.toLowerCase();//str1 = "abcd"
String str2 = str.toUpperCase();//str2 = "ABCD"

8. Replacement of characters in the string

1) public String replace(char oldChar, char newChar)//Replace all oldChar characters in the current string with character newChar and return a new string.

2) public String replaceFirst(String regex, String replacement)//This method replaces the first substring encountered in the current string that matches the string regex with the content of character replacement. It should be A new string is returned.

3) public String replaceAll(String regex, String replacement)//This method replaces all substrings encountered in the current string that match the string regex with the content of character replacement. The new string should be String returned.

String str = "asdzxcasd";
String str1 = str.replace('a','g');//str1 = "gsdzxcgsd"
String str2 = str.replace("asd","fgh");//str2 = "fghzxcfgh"
String str3 = str.replaceFirst("asd","fgh");//str3 = "fghzxcasd"
String str4 = str.replaceAll("asd","fgh");//str4 = "fghzxcfgh"

9. Other methods

1)String trim()//Truncate the spaces at both ends of the string, but do not process the spaces in the middle.

String str = " a bc ";
String str1 = str.trim();
int a = str.length();//a = 6
int b = str1.length();//b = 4

2) boolean statWith(String prefix) or boolean endWith(String suffix)//Used to compare the starting character or substring prefix and the ending character or substring suffix of the current string to see if they are the same as the current string The strings are the same, and the starting position offset of the comparison can also be specified in the overloaded method.

String str = "abcdef";
boolean a = str.statWith("ab");//a = true
boolean b = str.endWith("ef");//b = true

3)contains(String str)//Determine whether parameter s is included in the string and return a Boolean value.

String str = "abcdef";
str.contains("ab");//true
str.contains("gh");//false

4)String[] split(String str)//Use str as the delimiter to decompose the string, and the decomposed character string is returned in the string array.

String str = "abc def ghi";
String[] str1 = str.split(" ");//str1[0] = "abc";str1[1] = "def";str1[2] = "ghi";

10. Type conversion

String to basic type

There are Byte, Short, Integer and Float in the java.lang package , Calling method of Double class:

public static byte parseByte(String s)
public static short parseShort(String s)
public static short parseInt(String s)
public static long parseLong(String s)
public static float parseFloat(String s)
public static double parseDouble(String s)
int n = Integer.parseInt("12");
float f = Float.parseFloat("12.34");
double d = Double.parseDouble("1.124");

Convert basic type to string

String class provides String valueOf() method, which is used to convert basic type to string type

static String valueOf(char data[])
static String valueOf(char data[], int offset, int count)
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(float f)
static String valueOf(double d)
//将char '8' 转换为int 8
String str = String.valueOf('8');
int num = Integer.parseInt(str);

Base conversion

Use the methods in the Long class to obtain various base conversion methods between integers:

Long.toBinaryString(long l)//二进制
Long.toOctalString(long l)//十进制
Long.toHexString(long l)//十六进制
Long.toString(long l, int p)//p作为任意进制

Related learning recommendations:javaBasic Tutorial

The above is the detailed content of How to use java string?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software