Seven ways to use a string in Java

Source: Internet
Author: User

This is a day or two to learn some of the uses of string, remember in the interview in Beijing, the other people on the test in the examination of the test paper contains the use of string method, because at that time the string method is not familiar with the ambiguous answer to others, now after learning, think about all feel ashamed ah, hey, But fortunately, now the basic usage has been basically mastered, do these notes hope for their own or reading friends have some help.

The string class is useful for describing string things.
Then it provides several ways to manipulate the string

Here are seven ways to use string, note Oh, remember to check the Java API documentation from time to time, which is also described in detail

1, get
1.1: The number of characters contained in the string, which is the length of the string.
int length (): Get length
1.2: Get a character from the position according to the position.
char charAt (int index)
1.3: Gets the position of the character in the string according to the character.
int indexOf (int ch): Returns the position in which CH first appears in the string.
int indexOf (int ch,int fromindex): Gets the position that CH appears in the string, starting at the Fromindex specified position.

int indexOf (String str): Returns the position in which Str appears for the first time in a string.
int indexOf (String str,int fromindex): Gets the position that STR appears in the string, starting at the Fromindex specified position.
1.4:int LastIndexOf (String str): Reverse indexing.


2, Judge
2.1: Whether a string contains a substring.
Boolean contains (str);
Special: IndexOf (str): You can index STR for the first occurrence, and if you return-1, that STR is not present in the string.
Therefore, it can also be used to determine whether the specified is contained.
if (Str.indexof ("a")!=1)

Moreover, the method can be used to judge or obtain the position that appears.

2.2: There is content in the string.
Boolean IsEmpty (): The principle is to determine whether the length is 0.
2.3: Whether the string begins with the specified content.
Boolean startswith (str);
2.4: Whether the string ends with the specified content.
Boolean endsWith (str);
2.5: Determines whether the character content is the same, and the Equals method in the object class is overwritten.
Boolean equals (str);
2.6: Determine whether the content is the same and ignore case.
Boolean.equalsignorecase ();

3. Conversion.
3.1: Converts a character array into a string.
Constructor: String (char[])
String (Char[],offset,count): Converts a part of a character array into a string

static method:
Static String copyvalueof (char[]);
Static String copyvalueof (char[] data,int offset,int count);

Static String valueof (char[]);

3.2: Turn the string into a character group
Char[] ToCharArray ();

3.3: Converts a byte array into a string.
String (byte[])
String (Byte[],offset,count): Converting a portion of a byte array into a string

3.4: Converts a string into a byte array.
Byte[] GetBytes ()

3.5: Turn the base data type into a string,
static String valueof (int)
Static String valueof (double)

3+ "" is the same as the value of string.valueof (3)

Special: Strings and byte arrays can be encoded during conversion.

4. Replace
String replace (Oldchar,newchar);

5. Cutting
String[] Split (regex);

6. Sub String. Gets the part of the string
String subString (begin);
String subString (begin,end);

7. Convert, remove spaces, compare.
7.1: Turn the string into uppercase or lowercase
String touppercsae () Large-turn small
String tolowercsae () Small Turn large

7.2: Remove multiple spaces at both ends of the string
String trim ();

7.3: A natural order comparison of two strings
int CompareTo (string);

See the following code, which is for one by one examples of the above string seven usages:


Class Stringmethoddemo
{
public static void Method_zhuanhuan_qukong_bijiao ()
{
String s = "Hello Java";

The print result is: (There are spaces between Hello and Java front and back doors) Hello Java
SOP (S.touppercase ());

The print result is: (There are spaces between Hello and Java front and back doors) Hello Java
SOP (S.tolowercase ());

Print and result: "Hello Java" with no spaces
SOP (S.trim ());

The upper case of the comparison, the print result is: 1, because B corresponds to the ASCII value is 98,
A corresponds to 97, so b-a=1
String S1 = "abc";
String s2 = "AAA";
SOP (S1.compareto (S2));

}

public static void Method_sub ()
{
String s = "abcdef";

The print result is: Cdef, starting at the specified position to the end. If the corner mark does not exist, the string angle appears out of bounds.
SOP (S.substring (2));

The result is a CD that contains a header and does not contain a tail.
SOP (S.substring (2,4));
}
public static void Method_split ()
{
String s = "Zhangsan,lisi,wangwu";

string[] arr = S.split (",");

for (int x=0; x<arr.length; x + +)
{
SOP (Arr[x]);
}
}

public static void Method_replace ()
{
String s = "Hello java";

String S1 = s.replace (' A ', ' n ');
String S1 = s.replace (' W ', ' n '); If the character you want to replace does not exist, return the original string

String S1 = s.replace ("java", "World");//print Result: Hello World

SOP ("s=" +s); The print result is: Hello Java because once the string is initialized, the value cannot be changed
SOP ("s1=" +s1);//print Result: Hello JNVN

}

public static void Method_trans ()
{
Char[] arr = {' A ', ' B ', ' C ', ' d ', ' e ', ' f '};

string s = new string (arr,1,3);

SOP ("s=" +s);//print Result: BCD

String S1 = "ZXCVBNM";
char[] CHS = S1.tochararray ();

for (int x=0; x<chs.length; x + +)
{
SOP ("Ch=" +chs[x]);//print Result: ch=z,x,c,v,b,n,m
}
}

public static void Method_is ()
{
String str = "Arraydemo.java";

Determine if the file name is the beginning of the array word
SOP (Str.startswith ("Array"));

Determine if the file name is a. java file
SOP (Str.endswith (". Java"));

Determine if the file contains a demo
SOP (Str.contains ("Demo"));
}

public static void Method_get ()
{
String str = "ABCDEAKPF";

Length
SOP (Str.length ());

Get characters from index
SOP (Str.charat (4));
SOP (Str.charat (40)), Stringindexoutofboundsexception (String Corner-crossing exception) occurs when a corner mark that does not exist in the string is accessed

Get an index from a character
SOP (Str.indexof (' a '));
SOP (Str.indexof (' A ', 3));//printing is 5, because the corner Mark 3 is D,
So start looking at a, and the 5th corner is a.
SOP (Str.indexof (' t ', 3)) Print:-1, if no corner mark is found, return-1

Reverses the position in which a character appears (from the right to the left, but the angle or start from the left)
SOP (Str.lastindexof ("a"));
}

public static void Main (string[] args)
{
Method_zhuanhuan_qukong_bijiao ();
Method_sub ();
Method_split ();
Method_replace ();
Method_trans ();
Method_is ();
Method_get ();


/*
String S1 = "abc";
String s2 = new String ("abc");

String s3 = "ABC";
System.out.println (S1==S2);
System.out.println (S1==S3);
*/
}

public static void Sop (Object obj)
{
System.out.println (obj);
}
}

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.