I. Basic concepts of Java string classes
In the JAVA language, String data is actually implemented by the string class. Java string classes are divided into two categories: one is an invariant string whose length will not change in the program; The second is a variable string whose length will change in the program. In order to store and maintain these two kinds of strings, the Java environment provides
String and StringBuffer two classes.
First, create a string.
Example: Stringstr=new ("This is a string");
Or Stringstr= "This is a string";
Secondly, get the related information of the string object.
1. Get the length of the string by calling the length () method.
Example:
String str= "This is a string";
int len = str . length();
2. The capacity () method of the StringBuffer class is similar to the length () method of the String class, but it tests the size of the memory space allocated to the StringBuffer instead of the currently used memory space.
3. If you want to determine the position of the specified character or substring in a given string, you can use the indexOf () and lastIndexOf () methods.
String str= "This is a string";
int index 1 = str . index of(" I "); ? //index=2
Intindex2=str.indexOf('i ',index+ 1); ? //index2=5
intindex 3 = str . lastindexof(" I "); ? //index3= 15
intindex 4 = str . index of(" String "); ? //index4= 10
Third, modify the variable string
The StringBuffer class provides three methods to modify variable strings, and to insert and change characters at specific positions in the middle of strings.
1. append after the string: use the append () method to add various objects to the string.
2. insert in the middle of the string: use the insert () method. example
String buffer str = new String buffer(" this is a String ");
Str.insert(9," test ");
system . out . println(str . tostring());
The output of this code is: This is a test string.
3. Change the character in a certain position and use the setCharAt () method.
string buffer sb = new string buffer(" aaaaaa ");
sb.setCharAt(2,“b”); ? //result aabaaa