String
String is a class, not a basic data type.
Method for creating a String object
1. String S = "hello ";
2. String S = new string ("hello ");
3. Char chars [] = {'x', 'y', 'z '};
String S1 = new string (chars );
String S2 = new string (chars, 0, 2 );
"=" And "equals ()"
=: Determines the address of two strings in the memory, that is, whether the string object is the same
Equals ():Check whether the characters that constitute the string are completely consistent
Connection string
- Use "+"
- Use Concat ()
String S = new string ("hello ,");
String name = new string ("James! ");
String sentence = S. Concat (name );
System. Out. println (sentence );
Stringbuffer stringbulider
It is used to store and operate variable data consisting of multiple characters and is usually used to dynamically construct character data.
Statement
Stringbuffer ST = new stringbuffer (); // create a null stringbuffer object
Stringbuffer ST = new stringbuffer (10); // create an object with the specified initial length
Stringbuffer ST = new stringbuffer ("AAA"); // create a variable to store the string aaa
Use
St. tostring (); // convert to string type
St. append ("***"); append the string
Differences
Stringbuffer variable string thread security, multithreading
Stringbuilder is the fastest, with a single thread
Example: randomly generate Verification Code
Public class string01 {
Public static void main (string [] ARGs ){
String STR = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 ";
Stringbuilder S = new stringbuilder ();
Int Len = 4;
For (INT I = 0; I <= Len; I ++ ){
Random r = new random ();
Int P = R. nextint (Str. Length ());
S. append (Str. charat (p ));
}
System. Out. println (S. tostring ());
}
}
Randomly generate image names (Based on Time)
Public class string02 {
Public static void main (string [] ARGs ){
String fn = "aaa-ffff.jpg ";
String ext = fn. substring (fn. lastindexof ('.'));
String newfile = new simpledateformat ("yyyymmddhhmmsss"). Format (new date () + ext;
String n2 = UUID. randomuuid (). tostring () + ext;
System. Out. println (N2 );
}
}
// UUID randomly generates a number of strings with different values
// Formatting time simpledateformat ("yyyymmddhhmmsss"). Format (new date ())
Show today's day of the week
Public class string03 {
Public static void main (string [] ARGs ){
String week = "day, one, two, three, four, five, six ";
String [] wk = week. Split (","); // splits the string based on the matching of the given regular expression.
// Date d = new date ();
// String n = "today is: Week" + wk [D. getday ()];
Calendar c = calendar. getinstance ();
// System. Out. println (C. Get (calendar. day_of_week ));
String n = "today is: Week" + wk [C. Get (calendar. day_of_week)-1];
System. Out. println (N );
}
}
Examples of Common Extraction Methods
Other string operations
Simple string operations