Collation of string operations in java

Source: Internet
Author: User

Collation of string operations in java

I recently participated in the written examination of various major companies and found many programming questions related to string operations. I did not have a solid grasp of them. So I found some information on the Internet and made a summary.

I. Basic concepts of Java string classes

In JAVA, String data is actually implemented by the String class. Java string classes are divided into two types: one is a variable string that will not be changed in the program length; the other is a variable string that will be changed in the program length. The Java environment provides two classes: String and StringBuffer to store and maintain these two types of strings.
1. Create a string
Example: String str = new (This is a String );

Or String str = This is a String;

2. obtain information about the string object.
1. Call the length () method to obtain the String length.
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 she tests the size of the memory space allocated to the StringBuffer, rather than the memory space currently used.
3. You can use the indexOf () and lastIndexOf () methods to determine the position of a specified character or substring in a given string.

String str = This is a String;
Int index1 = str. indexOf (I); // index = 2
Int index2 = str. indexOf ('I', index + 1); // index2 = 5
Int index3 = str. lastIndexOf (I); // index3 = 15
Int index4 = str. indexOf (String); // index4 = 10


3. Comparison and operation of String objects
1. Comparison of String objects
The equals () method of the String class is used to determine whether two strings are equal.

String str = This is a String;
Boolean result = str. equals (This is another String );
// Result = false


2. Access to String objects
A. The charAt () method is used to obtain characters at the specified position.

String str = This is a String;
Char chr = str. charAt (3); // chr = I


B. The getChars () method is used to obtain a part of the string.

Public void getChars (int srcBegin, int srcEnd, char [] dst, int dstBegin)
String str = This is a String;
Char chr = new char [10];
Str. getChars (5, 12, chr, 0); // chr = is a St


C. subString () is another method for extracting strings. It can specify where to start extracting strings and where to end.
3. Operation string
A. replace () can replace one character in A string with another.

String str = This is a String;
String str1 = str. replace ('T', 'T'); // str1 = this is a String


B. concat () can combine two strings into one.

String str = This is a String;
String str1 = str. concat (Test); // str1 = This is a String Test


C. The toUpperCase () and toLowerCase () methods are used to convert the case sensitivity of strings.

String str = this is a string;
String str1 = str. toLowerCase (); // str1 = this is a string;


D. trim () can remove spaces at the beginning and end of a string.

String str = This is a String;
String str1 = str. trim (); // str1 = This is a String


E. The String class provides the static method valueOf (), which can convert any data object type into a String. For example

System. out. println (String, ValueOf (math, PI ));


4. Modify variable strings
The StringBuffer class provides three methods for modifying variable strings, including inserting and changing characters at a certain position in the middle of a string.
1. append the object to the string: append () to add various objects to the string.
2. insert in the middle of the string: Use the insert () method. Example

StringBuffer str = new StringBuffer (This is a String );
Str. insert (9, test );
System. out. println (str. toString ());


This code output is: This is a test String
3. Use the setCharAt () method to change the character of a location.

StringBuffer sb = new StringBuffer (aaaaaa );

Sb. setCharAt (2, "B"); // result aabaaa

 


2. string segmentation

1. Use the split method of the string class for segmentation

/***** // Use the string split method for segmentation
* @ Param str the string to be split
* @ Param sdelimiter delimiter
* @ Return
*/
Public String [] splitString (String str, String sdelimiter )...{
String [] array = str. split (sdelimiter );
Return array;
}

2. Use StringTokenizer to separate strings

/*** // ** Use StringTokenizer to separate strings
* @ Param str the string to be split
* @ Param sdelimiter delimiter
* @ Return
*/
Public String [] useStringTokenizer (String str, String sdelimiter )...{
StringTokenizer token = new StringTokenizer (str, sdelimiter );
String [] array = new String [token. countTokens ()];
Int I = 0;
While (token. hasMoreTokens ())...{
Array [I] = token. nextToken ();
I ++;
}
Return array;
}

Iii. Sort string Arrays

/***** // Sort the String Array
* @ Param str original string array
* @ Param flag = 0: ordered flag = 1: inverted
* @ Return the sorted String Array
*/
Public String [] sort (String [] str, int flag )...{
If (str = null | str. length = 0)
Throw new IllegalArgumentException ();
String temp = str [0];
// Ordered, from small to large
If (flag = 0 )...{
For (int I = 0; I For (int j = I + 1; j If (str [I]. compareTo (str [j])> 0 )...{
Temp = str [I];
Str [I] = str [j];
Str [j] = temp;
}
}
}
}
Else if (flag = 1)... {// sort in reverse order
For (int I = 0; I For (int j = I + 1; j If (str [I]. compareTo (str [j]) <0 )...{
Temp = str [I];
Str [I] = str [j];
Str [j] = temp;
}
}
}
}
Return str;
}

4. Use Hashtable to collide with strings

Use hashtable to filter strings and compare two character arrays to filter string arrays.

1. In some string arrays, there are often repeated records, such as mobile phone numbers. We can use Hashtable to filter them.

Public String [] checkArray (String [] str )...{
Hashtable Hash = new Hashtable ();

For (int I = 0; I If (! Hash. containsKey (str [I])
Hash. put (str [I], str [I]);
}

Enumeration enumeration = hash. keys ();
String [] str_new = new String [hash. size ()];
Int I = 0;

While (enumeration. hasMoreElements ())...{
Str_new [I] = enumeration. nextElement (). toString ();
I ++;
}
Return str_new;
}


Example:
String [] mobile = {13811071500,13811071500, 13811071501,13811071503, 13811071501 };
Mobile = checkArray (mobile );
For (int I = 0; I System. out. println (mobile [I]);
Output result:
13811071503
13811071501
13811071500
2. A and B are string arrays. Find the strings that exist in A and do not exist in B.
Public String [] compareArray (String [] A, String [] B ){
Hashtable Hash = new Hashtable ();
Hashtable Hash_new = new Hashtable ();

For (int I = 0; I Hash. put (B [I], B [I]);

For (int I = 0; I if (! Hash. containsKey (A [I])
Hash_new.put (A [I], A [I]);
}

String [] C = new String [hash_new.size ()];
Int I = 0;
Enumeration enumeration = hash_new.keys ();

While (enumeration. hasMoreElements ()){
C [I] = enumeration. nextElement (). toString ();
I ++;
}
Return C;
}
Example:
String [] mobile1 = {13811071500,13811071501, 13811071502,13811071503, 13811071504 };
String [] mobile2 = {13811071500,13811071505, 13811071502,13811071506, 13811071504 };
String [] mobile3 = compareArray (mobile1, mobile2 );
For (int I = 0; I System. out. println (mobile [I]);
Output result:
13811071503
13811071501
Problems:
Every time it is in reverse order, You Can slightly change the program to a forward order.

3. filter out a specific string in a string array.

/*** // Checks a string array. if it contains a specific string, it is deleted from the array.
Returns the remaining string array.
* @ Param str_array String Array
* @ Param str_remove the string to be deleted
* @ Return: The filtered string
*/
Public String [] removeStrFromArray (String [] str_array, String
Str_remove )...{
Hashtable Hash = new Hashtable ();
For (int I = 0; I If (! Str_array [I]. equals (str_remove ))
Hash. put (str_array [I], str_array [I]);
}
// Generate a new array
String [] str_new = new String [hash. size ()];
Int I = 0;
Enumeration enumeration = hash. keys ();
While (enumeration. hasMoreElements ())...{
Str_new [I] = enumeration. nextElement (). toString ();
I ++;
}
Return str_new;
}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.