Java to String Operations Encyclopedia

Source: Internet
Author: User
Tags chr stringbuffer

A. Java String class Basic concepts

In the Java language, string data is actually implemented by the string class. Java string classes fall into two categories: one is the invariant string that is not changed in the program, and the second class is a variable string that is changed in length in the program. In order to store and maintain these two types of strings, the Java environment providesStringAndStringBufferTwo classes.
first, create a string
Example: Stringstr=new ("This is a String");

Or stringstr= "This is a String";

Second, get the information about the string object
1. By callingLength ()method to get the length of the string.
Cases:

String Str= "Thisis a string";
int Len =str.length ();

2.StringBuffer Class ofcapacity ()Method and the String classLength ()The method is similar, but she tests the size of the memory space allocated to StringBuffer, rather than the memory space currently being used.
3. If you want to determine the position of a specified character or substring in a string at a given string, you can use theindexOf ()AndLastIndexOf ()Method.

String Str= "Thisis a string";
Int index1 =str.indexof ("I"); index=2
Intindex2=str.indexof (' i ', index+1); Index2=5
Intindex3=str.lastindexof ("I"); Index3=15
Intindex4=str.indexof ("String"); index4=10


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= "Thisis a string";
Boolean Result=str.equals ("This is another String");
Result=false


2. Access to a String object
A, methodcharAt ()The character used to get the specified position.

String Str= "Thisis a string";
Char Chr=str.charat (3); Chr= "I"


B, methodGetChars ()Used to get part of a string of strings

Public voidgetchars (int srcbegin,intsrcend,char[]dst,intdstbegin)
String Str= "Thisis a string";
Char chr =new char[10];
Str.getchars (5,12,chr,0); Chr= "Isa St"


CsubString ()is another way to extract a string, which specifies where to start extracting the string and where to end it.
3. Action string
Areplace ()method to replace a character in a string with another character.

String Str= "Thisis a string";
String str1=str.replace (' t ', ' t '); Str1= "Thisis a String"


The B, concat () method can combine two strings into a single string.

String Str= "Thisis a string";
String str1=str.concat ("Test"); Str1= "Thisis a String Test"


CtoUpperCase ()AndtoLowerCase ()method to implement a string-case conversion, respectively.

String str= "Thisis A string";
String str1=str.tolowercase (); Str1= "Thisis a string";


The D, Trim () method removes the spaces at the beginning and end of the string.

String Str= "Thisis a string";
String Str1=str.trim (); Str1= "This is a String"


E, String class provides static methodsvalueof (), which converts any type of data object to a string. Such as

System.out.println (string,valueof (MATH,PI));


iv. modifying variable strings
The StringBuffer class provides 3 methods for modifying a variable string, inserting and changing the character of a position in the middle of the string.
1. Append after string: WithAppend ()method to add a variety of objects to a string.
2. Inserting in the middle of a string:Insert ()Method. Cases

StringBuffer str=new StringBuffer ("Thisis a String");
Str.insert (9, "test");
System.out.println (Str.tostring ());


This code output is: Thisis a test String
3. Change the character of a position, usingSetcharat ()Method.

StringBuffer SB =new stringbuffer ("aaaaaa");

Sb.setcharat (2, "B"); Results AABAAA


Two. String segmentation

1. Using the split method of string class to split

/** *//** using the split method of string to segment
* @param str to be split string
* @param sdelimiter Separator
* @return
*/
Public string[] Splitstring (String str,string sdelimiter) ... {
String[] Array=str.split (sdelimiter);
return array;
}

2. Using StringTokenizer for string segmentation

/** *//** uses StringTokenizer for string segmentation
* @param str to be split string
* @param sdelimiter Separator
* @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;
}

three. String array sorting

/** *//** to sort a string array
* @param str Original string array
* @param flag flag=0: Sequential sort flag=1: Descending order
* @return sorted array of strings
*/
Public string[] Sort (string[] str,int flag) ... {
if (str==null| | str.length==0)
throw new IllegalArgumentException ();
String Temp=str[0];
In order, that is, from small to large
if (flag==0) ... {
for (int i=0;i<str.length-1;i++) ... {
for (int j=i+1;j<str.length;j++) ... {
if (Str[i].compareto (Str[j]) >0) ... {
Temp=str[i];
STR[I]=STR[J];
Str[j]=temp;
}
}
}
}
else if (flag==1) ... {//reverse order
for (int i=0;i<str.length-1;i++) ... {
for (int j=i+1;j<str.length;j++) ... {
if (Str[i].compareto (Str[j]) <0) ... {
Temp=str[i];
STR[I]=STR[J];
Str[j]=temp;
}
}
}
}
return str;
}

four. Use Hashtable to collide a string

Filter strings using Hashtable, Comparison of two-character arrays, filtering of string arrays

1. In some string arrays, there are often duplicate records, such as cell phone number, we can filter it by Hashtable

Public string[] Checkarray (string[] str) ... {
Hashtable<string, string> hash=new hashtable<string, string> ();

for (int i=0;i<str.length;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<mobile.length;i++)
System.out.println (Mobile[i]);
The output results are:
13811071503
13811071501
13811071500
2.a,b are all array of strings to find strings that exist in A and that do not exist in B
Public string[] Comparearray (string[] a,string[] B) {
Hashtable<string, string> hash=newhashtable<string, string> ();
Hashtable<string, String>hash_new=new hashtable<string, string> ();

for (int i=0;i<b.length;i++)
Hash.put (B[i], b[i]);

for (int i=0;i<a.length;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<mobile3.length;i++)
System.out.println (Mobile[i]);
Output results:
13811071503
13811071501
The problems that exist:
Each time is in reverse order, you can change the program slightly, into a positive sequence.

3. Filter out a particular string in an array of strings

/** *//** examines an array of strings and, if it contains a particular string, deletes the string from the array
In addition, returns the remaining array of strings
* @param str_array string array
* @param str_remove The string to be deleted
* @return Filtered string
*/
Public string[] Removestrfromarray (string[] str_array,string
Str_remove) ... {
Hashtable<string, string> hash=new hashtable<string, string> ();
for (int i=0;i<str_array.length;i++) ... {
if (!str_array[i].equals (Str_remove))
Hash.put (Str_array[i], str_array[i]);
}
To 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;
}

Related Article

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.