Java Api_string Class

Source: Internet
Author: User
Tags array to string


String class

Overview and Construction methods of the 1.String class and related methods

(1). Overview of the String class
A string is a series of data consisting of more than one character. It can also be seen as a character array.

(2). How to construct a string class
Public String (): null parameter construct
public string (byte[] bytes): Converts a byte array into a string
public string (byte[] bytes,int index,int length): Converts a portion of a byte array into a string
public string (chart[] value): Convert character array to string
public string (chart[] Value,int index,int count): Turns a part of a character array into a string
public string (string original): Convert string constant value to string


Examples of Use:
public static void Main (string[] args) throws Clonenotsupportedexception {
Char[] chs={' A ', ' B ', ' C ', ' d ', ' e '};
String Str=new string (CHS);
System.out.println (str);
}
Output Result:
Abcde

(3). Face question 1 of the String class
String S=new string ("Hello"); and string s= "Hello"; what's the difference?
String S=new string ("Hello");
Two objects are created, one is the string constant that first created "Hello", and then an object s (The new thing is in heap memory), and the address of the heap memory is referenced.
String s= "Hello"
Only one object is created, referring to the address inside the string constant pool inside the method area.

(4). Face question 2 of the String class
Read the program to write the results and analyze:
public static void Main (string[] args) throws Clonenotsupportedexception {
String str1= "Hello";
String str2= "World";
String str3= "HelloWorld";
System.out.println (STR3==STR1+STR2);
System.out.println (Str3.equals (STR1+STR2));
}
Output Result:
False
True

Analysis:
"= =": Compare the reference type comparison is the address value is the same
equals string type overrides the equal () method, comparing whether the content is the same

String if the variable is added, first open the space, and then splicing
If the string is a constant addition, it is added first, then the constant pool inside the search, if there is a direct return, otherwise created.


(5). The judging function of the string class
Boolean equals (Object obj): Comparing the contents of a string is not the same, case-sensitive
Boolean equalsignorecase (String str): Compares whether the contents of a string are the same, ignoring case
Boolean contains (String str): Determines whether a string contains a specific string
Boolean startwidth (String str): Determines whether a string begins with a specified string
Boolean endswidth (String str): Determines whether a string ends with a specified string
Boolean isEmpty (); Determines whether the string is empty

Precautions for use:
String s= ""; Method can be called
String S=null; Methods cannot be called
The string content is empty (there is an object but no content) and the string object is empty (indicating that no even object exists)


(6). Get function of String class
int length (): Gets the length of the string
char charAt (int index): Gets the character at the specified index position
int indexOf (int ch): Returns the index of the first occurrence of the specified character in this string (note the character)
int indexOf (String str): Returns the index of the first occurrence of the specified string in this string (note that it is a string)
int indexOf (int ch,int formindex): Returns the index at the first occurrence of the specified character from the specified position in this string
int indexOf (String str,int formindex): Returns the index at the first occurrence of the specified string from the specified position in this string
String subString (int start): Intercepts the string starting at the specified position. Default to End
String subString (int start, int end): Intercepts the string from the specified position to the end of the specified position.


(7). Examples of basic uses of the String class

A: Variable gets every character in a string
Basic methods
How to get every single character
char chartat (int index);
Gets the number of characters
int Length ()

Code:
public static void Main (string[] args) {
String str = "HelloWorld";
for (int i=0;i<str.length (); i++) {
System.out.println ("+i+" obtains the character is: "+str.charat (i));
}
}

Output Result:
The No. 0 character obtained is: H
The 1th character obtained is: E
The 2nd character obtained is: l
The 3rd character obtained is: l
The 4th character obtained is: O
The 5th character obtained is: W
The 6th character obtained is: O
The 7th character obtained is: R
The 8th character obtained is: l
The 9th character obtained is: D

B: Count the case, number in the string
Use basic methods
char chartat (int index);
int length ();

Uppercase and lowercase digital ASCII code
0 48
A 65
A 97

Judging the use of code
if (ch>= ' 0 ' &&ch<= ' 9 ') {
numbercount++;
}
if (ch>= ' a ' &&ch<= ' Z ') {
smallcount++;
}
if (ch>= ' a ' &&ch<= ' a ') {
bigcountcount++;
}

Code implementation:
public static void Main (string[] args) {
//define the string to be searched
string str= "HeLLoWorld129090";
//define three statistics
int bigcount=0;
int smallcount=0;
int numbercount=0;
//Traversal string, get each character
for (int i=0;i<str.length (); i++) {
Char ch=str.charat (i);
//Determine if it belongs to which type
if (ch >= ' a ' &&ch<= ' Z ') {
smallcount++;
} else if (ch>= ' A ' &&ch<= ' Z ') {
bigcount++;
} else if (ch>= ' 0 ' &&ch<= ' 9 ') {
numbercount++;
}
}
//Output
System.out.println (str+: Uppercase: "+bigcount+"---lowercase letters: "+smallcount+"---numbers have "+numbercount+" ");
}

Output is:
HeLLoWorld129090: The uppercase letters are: 4---lowercase letters: 6---digits have 6


(8). Conversion function for Strings
byte[] getBytes (): Converting a string to a byte array
char[] ToCharArray (): Converting a string into a character array
static string valueOf (char[] CHS): Converts a character array to a string
static string valueOf (int i): Converts data of type int to string
Note: The ValueOf method of the string class can convert any type of data into a string
String toLowerCase (): Converts a string to lowercase
string touppercase (): Converts a string to uppercase
String concat (String str): string concatenation


(9). Other features of the string class
Replace function
String replace (char Old,char new): Converts the old character into a new character
string replace (string old,string new): Converts an old string into a new string

Two-side space to remove characters
string trim ()

Compare two strings in dictionary order
int compareTo (string str)
int Comparetoignorecase (String str)

Examples of Use:
public static void Main (string[] args) {
String str= "HelloWorld";
String str1= "ABC";
String str2= "ABCD";
System.out.println (Str.replace ("H", ""));
System.out.println (str.replace ("Hello", ""));
System.out.println (Str1.compareto (str2));
System.out.println (Str1.trim ());
System.out.println (Str1.comparetoignorecase (str2));
}
The output result is
Elloworld
World
-68
Abc
-68

(10). Examples of basic use of strings 2

A: String reversal
function Result: keyboard input "abc", output result is "CBA"

Design Analysis:
A: keyboard input a string
B: Define a new string
C: Backwards traversal of this string
The length () method and the Charat () combination
Convert a string to a character array
D: Use a new string to stitch each character together
E: Output New string

Code implementation:
public class Test {
public static void Main (string[] args) {
Keyboard input
@SuppressWarnings ("resource")
Scanner SN =new Scanner (system.in);
System.out.println ("Please enter a string:");
String Line=sn.nextline ();
String s=reversestring (line);
SYSTEM.OUT.PRINTLN ("The result after the flashback is:" +s);
}

/**
* String reversal
* @author Administrator
* @param string str: Raw string
* @return String str: result string
*
*/
public static string reversestring (String str) {
Defining the return string
String result= "";
Convert a string to a character array
Char[] Chs=str.tochararray ();
Backwards traversal, getting every string
for (int i=chs.length-1;i>=0;i--) {
Use a new string to stitch each character together
Result +=chs[i];
}
return result;
}
}


B: Count the number of occurrences of a small string in a string

Code Design Analysis:
Defines a large string
Defines a small string

A: Define a statistic variable and initialize the value to 0
B: Find the first position in a small string in a large string now
If the index is-1, the small string does not appear in the large string
If the index is not-1, the description exists, the statistics variable + +
C: Take the length of the index + small string as the starting position to intercept the last large string, return a new string, and re-assign the value of the string to the large string
D: Return to process B

Code implementation
public class Test {
public static void Main (string[] args) {
Define a large string
String maxstring= "Javafjhfvsadvfkashjfvasjjavaalhsdfajavabs";
Defining small strings
String minstring= "Java";
int Count=getcount (maxstring, minstring);
System.out.println (minstring+ "The number of occurrences is:" +count);

}

/**
* Statistics large string occurrences of small strings
* @author Administrator
* @param string str: original string
* @return int: Returns the number of occurrences
*
*/
public static int GetCount (String maxstring,string minstring) {
Define a statistic variable
int count=0;
Find the first occurrence of a small string in a large string, and then copy
int Index=maxstring.indexof (minstring);
If the index is not-1, the description exists, the statistics variable + +
while ((Index=maxstring.indexof (minstring))!=-1) {
count++;
Maxstring=maxstring.substring (Index+minstring.length ());
}
return count;
}
}
Test results
The number of Java occurrences is: 3

Java Api_string Class

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.