Java string (unfinished)

Posted by helraizer on Fri, 07 Jan 2022 08:21:20 +0100

Strings in Java are multiple characters enclosed in double quotes. Characters in Java are encoded in Unicode.

If a single character is enclosed in double quotation marks, it represents a string, not a character.

Java SE provides three string classes: string, StringBuffer and StringBuilder. String is an immutable string, and StringBuffer and StringBuilder are variable strings.

The difference between an immutable string and a variable string is that when a string is spliced or modified, the immutable string will create a new string object, while the variable string will not create an object.

The immutable String class in Java is String, which belongs to Java Lang package, which is also a very important class in Java.

String(): creates and initializes a new string object using an empty string.

String(String original): use another string to create and initialize a new string object.

String (StringBuffer): create and initialize a new string object using a variable string object (StringBuffer).

String(StringBuffer builder): create and initialize a new string object using a variable string object (StringBuffer).

String(byte[] bytes): decodes the specified byte array using the default character set of the platform, and creates and initializes a new string object through the byte array.

String(char[] value): create and initialize a new string object through a character array.

String(char[] value, int offset, int count): create and initialize a new string object through the subarray of the character array; The offset parameter is the index of the first character of the subarray, and the count parameter specifies the length of the subarray.

The example code for creating a string object is as follows:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1=new String();
		String s2=new String("Hello World");
		String s3=new String("\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064");
		System.out.println("s2 = "+s2);
		System.out.println("s3 = "+s3);
		
		char chars[]= {'a','b','c','d','e'};
		String s4=new String(chars);
		String s5=new String(chars,1,4);
		System.out.println("s4 = "+s4);
		System.out.println("s5 = "+s5);
		
		byte bytes[]= {97,98,99};
		String s6=new String(bytes);
		System.out.println("s6 = "+s6);
		System.out.println("s6 String length = "+s6.length());
	}

}

Output results:

s2 = Hello World
s3 = Hello World
s4 = abcde
s5 = bcde
s6 = abc
s6 String length = 3

String pool: (code error, not mastered)

The immutable String constant in Java adopts String Pool management technology, which is a String resident technology.

The code is as follows:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s7=new String("Hello");
		String s8=new String("Hello");
		
		String s9="Hello";
		String s10="Hello";
		
		System.out.printf("s7 == s8 : %b%n, s7==s8");
		System.out.printf("s9 == s10: %b%n, s9==s10");
		System.out.printf("s7 == s9 : %b%n, s7==s9");
		System.out.printf("s8 == s9 : %b%n, s8==s9");
	}

}

Operation results:

s7 == s8 : Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%b'
	at java.util.Formatter.format(Unknown Source)
	at java.io.PrintStream.format(Unknown Source)
	at java.io.PrintStream.printf(Unknown Source)
	at helloworld.helloworld.main(helloworld.java:13)

String splicing:

Examples of string splicing are as follows:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1="Hello";
		//Connect using the + operator
		String s2=s1+" ";
		String s3=s2+"World";
		System.out.println(s3);
		
		String s4="Hello";
		//Use the + operator to connect, and support the + = assignment operator
		s4+=" ";
		s4+="World";
		System.out.println(s4);
		
		String s5="Hello";
		//Connect using concat method
		s5=s5.concat(" ").concat("World");
		System.out.println(s5);
		
		int age=18;
		String s6="Her ages is "+ age +" age old.";
		System.out.println(s6);
		
		char score='A';
		String s7="Her English score is "+score+".";
		System.out.println(s7);
		
		java.util.Date now=new java.util.Date();
		String s8="Today is "+now +".";
		System.out.println(s8);
	}

}

Output results:

Hello World
Hello World
Hello World
Her ages is 18 age old.
Her English score is A.
Today is Fri Jan 07 13:32:37 CST 2022.

String lookup:

indexOf and lastIndexOf methods are provided in the String class to find characters or strings. The return value is the position of the searched character or String, - 1 means it is not found.

Int indexOf(int ch): search the character ch from front to back and return the index where the character ch is found for the first time.
Int  indexOf(int  ch, int  fromIndex): search the character ch from front to back from the specified index, and return the index where the character ch is found for the first time.
int. indexOf(String str): search the string str from front to back, and return the index where the string str is found for the first time.
Int  indexOf(String str, int  fromIndex): search the string str from front to back from the specified index, and return the index where the string str is found for the first time.
Int # lastIndexOf(int # ch): search the character ch from back to front, and return the index where the character ch is found for the first time.
Int ^ lastIndexOf(int ^ ch, int ^ fromIndex): search the character ch from back to front from the specified index, and return the index where the character ch is found for the first time.
int. lastIndexOf(String str): search the string str from back to front, and return the index where the string str is found for the first time.
Int  lastIndexOf(String str, int  fromIndex): search the string str from the specified index, and return the index where the string str is found for the first time.

The example code of string lookup is as follows:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String sourceStr ="There is a string accessing example.";
		//Get string length
		int len= sourceStr.length();
		//Gets the character at index position 16
		char ch= sourceStr.charAt(16);
		
		//Find characters and substrings
		int firstChar1= sourceStr.indexOf('r');
		int lastChar1= sourceStr.lastIndexOf('r');
		int firstStr1= sourceStr.indexOf("ing");
		int lastStr1= sourceStr.lastIndexOf("ing");
		int firstChar2= sourceStr.indexOf('e', 15);
		int lastChar2= sourceStr.lastIndexOf('e', 15);
		int firstStr2=	sourceStr.indexOf("ing", 5);
		int lastStr2= sourceStr. lastIndexOf ("ing", 5);
		System.out.println("Original string:"+ sourceStr);
		System.out.println("String length:"+len);
		System.out.println("Characters of index 16:"+ch);
		System.out.println("Search from front to back r character,Find its index for the first time:" +firstChar1);
		System.out.println("Search from back to front r character,Find its index for the first time:" +lastChar1);
		System.out.println("Search from front to back ing character string,Find its index for the first time:" +firstStr1);
		System.out.println("Search from back to front ing character string,Find its index for the first time:" +lastStr1);
		System.out.println("Start at index 15,Search from front to back e character,Find its index for the first time:"+firstChar2);
		System.out.println("Start at index 15,Search from back to front e character,Find its index for the first time:"+lastChar2);
		System.out.println("Start at index 5,Search from front to back 1 ng character string,Find its index for the first time:"+firstStr2);
		System.out.println("Start at index 5,Search from back to front ing character string,Find its index for the first time:"+lastStr2);

	}

}

The output results are as follows:

Original string:There is a string accessing example.
String length:36
 Characters of index 16:g
 Search from front to back r character,Find its index for the first time:3
 Search from back to front r character,Find its index for the first time:13
 Search from front to back ing character string,Find its index for the first time:14
 Search from back to front ing character string,Find its index for the first time:24
 Start at index 15,Search from front to back e character,Find its index for the first time:21
 Start at index 15,Search from back to front e character,Find its index for the first time:4
 Start at index 5,Search from front to back 1 ng character string,First find its index: 14
 Start at index 5,Search from back to front ing character string,Find its index for the first time:-1

String comparison:

1. Compare equal

boolean equals(Object anObject): compare whether the contents of two strings are equal.

Boolean equalsignorecase (string otherstring): similar to the equals method, but ignoring case.

2. Compare size

Int CompareTo (string otherstring): compares two strings in dictionary order. If the parameter string is equal to this string, the return value is 0; If this string is smaller than the parameter string, a value less than 0 will be returned; If this string is larger than the parameter string, a value greater than 0 is returned.

int compareToIgnoreCase(String str): similar to compareTo, but ignoring case.

3. Compare prefix and suffix

boolean endsWith(String suffix): tests whether the string ends with the specified suffix.

boolean startsWith(String prefix): test whether some strings start with the specified prefix.

The example code of string comparison is as follows:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1=new String("Hello");
		String s2=new String("Hello");
		//Compare whether the string is the same reference
		System.out.println("s1==s2:"+(s1==s2));
		//Compare string contents for equality
		System.out.println("s1.equals(s2):"+(s1.equals(s2)));
		
		String s3="HELLO";
		//Ignore case and compare whether the string contents are equal
		System.out.println("s1.equalsIgnoreCase(s3):"+(s1.equalsIgnoreCase(s3)));
		
		//Compare size
		String s4="java";
		String s5="Swift";
		//Compare string size S4 > S5
		System.out.println("s4.compareTo(s5):"+(s4.compareTo(s5)));
		//Ignore case compare string size S4 < S5
		System.out.println("s4.compareToIgnoreCase(s5):"+(s4.compareToIgnoreCase(s5)));
		//Determine the file name in the folder
		String[] docFolder= {"java.docx","JavaBean.docx","Objecitive-C.xlsx","Swift.docx"};
		int wordDocCount=0;
		//Find the number of Word documents in the folder
		for(String doc:docFolder) {
			//Remove the front and back spaces
			doc=doc.trim();
			//Compare suffixes for docx string
			if(doc.endsWith(".docx")) {
				wordDocCount++;
			}
		}
		System.out.println("Folder word The number of documents is: "+wordDocCount);
		
		int javaDocCount=0;
		//Find the number of Java related documents in the folder
		for(String doc: docFolder) {
			//Remove the front and back spaces
			doc=doc.trim();
			//Convert all characters to lowercase
			doc=doc.toLowerCase();
			//Compare whether the prefix has a java string
			if(doc.startsWith("java")) {
				javaDocCount++;
			}
		}
		System.out.println("Folder Java The number of relevant documents is: "+javaDocCount);
	}

}

Output results:

s1==s2:false
s1.equals(s2):true
s1.equalsIgnoreCase(s3):true
s4.compareTo(s5):23
s4.compareToIgnoreCase(s5):-9
 Folder word Number of documents: 3
 Folder Java Number of relevant documents: 2

String interception:

String substring(int beginIndex): the substring intercepted from the specified index beginIndex to the end of the string.

String substring(int beginIndex, int endIndex): intercept the characters from the specified index beginIndex to the index endIndex-1. Note that the characters at the index beginIndex are included, but the characters at the index endIndex are not included.

The sample code of string interception method is as follows:

package helloworld;

public class helloworld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String sourceStr="There is a string accessing example.";
		//Intercept example Substring
		String subStr1=sourceStr.substring(28);
		//Intercept string substring
		String subStr2=sourceStr.substring(11,17);
		System.out.printf("subStr1= %s%n", subStr1);
		System.out.printf("subStr2=%s%n", subStr2);
		//Use the split method to separate strings
		System.out.println("-----use split method-----");
		String[] array= sourceStr.split(" ");
		for(String str:array) {
			System.out.println(str);
		}
	}

}

Output results:

subStr1= example.
subStr2=string
-----use split method-----
There
is
a
string
accessing
example.

Variable string:

Java provides two variable string classes, StringBuffer and StringBuilder, which are translated into "string buffer" in Chinese.

StringBuffer and StringBuilder:

String append:

String insertion, deletion and replacement

Topics: Java Back-end