Home > Java > javaTutorial > body text

How to use java string?

藏色散人
Release: 2020-09-17 15:47:01
Original
18722 people have browsed it

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的字符串
Copy after login

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);
Copy after login

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
Copy after login

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"
Copy after login

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
Copy after login

5. String link

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

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
Copy after login

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"
Copy after login

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"
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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";
Copy after login

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");
Copy after login

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);
Copy after login

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作为任意进制
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!