Java String FAQ

Source: Internet
Author: User


first, how to infer two string is it equal?? Use "= =" or "Equals ()"?

for string . "= =" is used to infer whether the address of two strings (objects) is the same, that is, whether the inference is an application of the same string.

Equals () is the inference that the values of two strings (objects) are equal, assuming that equality returns TRUE. Under normal circumstances. is using Equals () to infer that the values of two strings are equal, only if you need to infer whether two strings are the same object. Only use "= =".

<span style= "FONT-SIZE:18PX;" >string str1 = "abc"; String str2 = "abc"; String str3 = new String ("abc"); System.out.println (str1 = = str2);    TrueSystem.out.println (str1 = = STR3);    FalseSystem.out.println (Str1.equals (STR3));     Tru</span>

Second, how to implement the string and the basic data type of the load Exchange

First look at how to convert a string to the primary data type. 8 wrapper class (Integer,double ...) provides a corresponding method parsexxx (string str) to convert a string to the primary data type, such as the following:

String str1 = " 123 ";

String str2 = " 12.3 ";

String STR3 = " true ";

int     a = Integer.parseint (STR1); //123

Double d = double.parsedouble (str2); //12.3

Boolean flag = Boolean.parseboolean (STR3); //true

You may have met with a conversion using valueof(), such as the following:

String str1 = " 123 ";

String str2 = " 12.3 ";

String STR3 = " true ";

int a = integer.valueof (str1); //123

Double    d = double.valueof (STR2); //12.3

Boolean     flag = boolean.valueof (STR3); //true

Such a form is also OK. Just not using parsexxx directly() good, because integer.valueof () returns an integer type, and then converts it to the base data type by its own active container, the method prototype is as follows:

Public Static Integer valueOf (String s)

the note is. Method Boolean.parseboolean (STRINGSTR), which returns true only if STR is the string "true" (ignoring uppercase and lowercase). In other words, all other strings return false. Boolean.parseboolean ("yes") will return false.

Then come down and see how to convert the base data type to string, which can be converted using the String.valueof () method, such as the following:

int a = 123;

Double B = 13.05;

Boolean flag = true ;

String str1 = string.valueof (a); //123

String str2 = string.valueof (b); //13.05

String STR3 = string.valueof (flag); //true

At the same time there is a much simpler and quicker way to add "" directly after the basic data type. For example the following;

String str1 = a + ""; //a

String str2 = flag + ""; //true

Finally, let's talk about the conversion of the wrapper class , the same ability to convert the base data type to string, such as the following:

int a = 123;

Boolean flag = true ;

String str1 = integer.tostring (a); //123

String str2 = boolean.tostring (flag); //true

in fact, the string.valueof () method also calls the ToString () method of various wrapper classes, such as the following. Just String.valueof () is easier to use, because there is no need to infer which type of data it belongs to.

Public Static String valueOf (double d) {

return double.tostring (d); // the rest of the conversions are similar.

}

Third, how to cut the string

Cutting Strings in Java is done by means of a regular table. I'm just going to talk a little bit about how to cut, and I want to learn more about the normal form. Be able to click here.

First Look at a simple sample, such as the following using "-" to cut a string.

String str = " AA-BB-CC-DD ";

string[] res = str.split ("-"); //AA BB cc DD

It looks very easy, just need to find the cutting complex. If you want to use "C" as the cutting character, the output is aa-bb--dd. Another look at this is to use a space character (\s) to cut the string (SPACEBAR). tab or line break), such as the following:

String STR4 = " AA BB cc DD ";

string[] res = str4.split ("\\s"); //aa bb cc DD

It's a little different here. In Java , the backslash (\) has a special meaning to avoid confusion or anomalies. should use (\ \), like, look at using the "|" Cut strings,

String STR4 = " AA|BB|CC|DD ";

string[] res = str4.split ("\\|   "); //aa bb cc DD

Four, take the sub-string

String str = " ABCDEFG ";

str = str.substring (2, 5); //CDE

in the Java7 . SUBSTRING creates a string, assuming it is in JAVA6, that advocates the use of the following methods, for example:

String str = " ABCDEFG ";

str = str.substring (2, 5) + ""; //CDE

about The difference between substring in JAVA6 and Java7. Able to access relevant information.

V. How to convert a string to a date

String str = " 2014-6-27 ";

SimpleDateFormat format = New SimpleDateFormat ();

Format.applypattern ("yyyy-mm-dd");

Date date = Format.parse (str);

SYSTEM.OUT.PRINTLN (date);


six, String. The difference between Stringbuilder,stringbuffer

String Unlike StringBuilder , a string is created and cannot be changed again, StringBuilder is mutable. Can be changed after creation. The difference between StringBuilder and StringBuffer, StringBuffer is thread-safe, and the speed of operation relative to StringBuffer will be slower.

Vii. using strings in a switch statement

start from Java7 . The ability to use strings in a switch statement, such as the following:

Switch (str) {

Case " a":   

break;

case "b":

break;

}

Eight, let the string appear repeatedly

using Apache Commons Lang 's stringutils, this capability can be achieved:

String str = " 1234 ";

String repeated = Stringutils.repeat (str,3);

1234 1234 1234

in fact, the way is as follows, note that, because of the length of the reasons, and no matter what the exception, the specific operation can participate in the source code:

<span style= "FONT-SIZE:18PX;"   >public string Repeat (String Str,int repeattimes) {int inputlen = Str.length ();    Gets the length of the string int outputlen = Inputlen *repeattimes; Length of the output string switch (Inputlen) {///when the length is only 1 or 2 o'clock, select Use character operation directly, add efficiency case 1:retu            RN Repeat (Str.charat (0), repeattimes);                  Case 2:char ch0 = Str.charat (0);                  Char ch1 = Str.charat (1);                  char[] output = Newchar[outputlen];                        for (int i = RepeatTimes * 2-1;i>=0;) {output[i] =ch0;                        Output[i+1] =ch1;                  I +=2;            } return output.tostring ();                  Default:stringbuilder buf =new StringBuilder ();                  for (int i = 0;i <= repeatTimes-1; i++) {buf.append (str);            } return buf.tostring ();   }      }        Public String Repeat (char ch,int repeattimes) {char[] buf = Newchar[repeattimes];            for (int i = repeatTimes-1; I >=0; i--) {//copy repeattimes buf[i] = ch;      } return buf.tostring (); }</span>

Nine, how to calculate the number of occurrences of the specified character in a string

The same is the stringutils that uses Apache Commonslang , such as the following:

int n = stringutils.countmatches ("aaaabbbb", "a");

SYSTEM.OUT.PRINTLN (n);

10. On some sensitive information, why do you tend to use char[] instead of string?

When a string is created, it cannot be changed until it is reclaimed by the GC. GC recovery time cannot be predicted. Even if an object does not have a reference, it will need to be reclaimed at some time in the future. So string operates sensitive information, There is a risk of leakage. char[] It is not the same, we can directly control its elements through the program, general sensitive information is no longer practical, the array can be directly, and therefore more inclined to use char[] to save sensitive information such as password.

Java String FAQ

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.