A string of common Java objects

Source: Internet
Author: User
Tags array to string

Overview of the String class

Stringclass represents a string. All string literals (such as) in a Java program "abc" are implemented as instances of this class.
Strings are constants, and once they are assigned, they cannot be changed.

How to construct a string class

* Public String (): Empty construct
* public string (byte[] bytes): Convert byte array to string
* public string (byte[] bytes,int index,int length): Turns part of a byte array into a string
* public string (char[] value): Convert character array to string
* public string (char[] 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

Common face questions for string class

1. Determine if S1 and S2 that are defined as string types are equal
* String S1 = "abc";
* String s2 = "abc";
* SYSTEM.OUT.PRINTLN (S1 = = s2);
* SYSTEM.OUT.PRINTLN (S1.equals (S2));

= = Compares the object address, while equals compares the value. Are true. String S1 = "abc" is stored in a constant pool, and the constant pool is characterized if it is not created if it is already there, so S1 and S2 are the same object.


2. The following sentence creates several objects in memory?
* String S1 = new String ("abc");

Two, the first in a constant pool, and the second in the heap.


3. Determine if S1 and S2 that are defined as string types are equal
* String S1 = new String ("abc");
* String s2 = "abc";
* SYSTEM.OUT.PRINTLN (S1 = = s2);
* SYSTEM.OUT.PRINTLN (S1.equals (S2));

The second question indicates that the first is false and the second is true.


4. Determine if S1 and S2 that are defined as string types are equal
* String S1 = "a" + "B" + "C";
* String s2 = "abc";
* SYSTEM.OUT.PRINTLN (S1 = = s2);
* SYSTEM.OUT.PRINTLN (S1.equals (S2));

All two are true. The first is that because Java has a constant optimization mechanism, it is "ABC" directly during the compilation phase.


5. Determine if S1 and S2 that are defined as string types are equal
* String S1 = "AB";
* String s2 = "abc";
* String s3 = s1 + "C";
* SYSTEM.OUT.PRINTLN (s3 = = s2);
* SYSTEM.OUT.PRINTLN (S3.equals (S2));

The first one is false and the second is true. The first sentence and the second sentence are created in the constant pool in constant "AB", "ABC", the third sentence in the code of + is through the StringBuffer append method to connect S1 and "C", and then through the ToString method to convert to a string object, is a new object in the heap, is different from the S2 in a constant pool.

The judging function of the string class

* Boolean equals (Object obj): Compares the contents of strings for the same, case-sensitive
* Boolean equalsignorecase (String str): Compares the contents of a string for the same, ignoring case
* Boolean contains (String str): Determines whether a large string contains a small string
* Boolean StartsWith (String str): Determines whether a string begins with a specified string
* Boolean EndsWith (String str): Determines whether the string ends with a specified string
* Boolean isEmpty (): Determines whether the string is empty.

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.
* int indexOf (string str): Returns the index of the first occurrence of the specified string in this string.
* int indexOf (int ch,int fromIndex): Returns the index at the first occurrence of the specified character from the specified position in this string.
* int indexOf (string str,int fromIndex): Returns the index at the first occurrence of the specified string from the specified position in this string.
* LastIndexOf
* String substring (int start): Intercepts the string starting at the specified position, from the default to the end.
* String substring (int start,int end): Intercepts the string from the specified position to the specified position.

Case Study 1: Traversing strings
     Public Static void Main (string[] args) {        = "Heima";              for (int i = 0; i < s.length (); i++) {                        System.out.println (S.charat (i));                }    }
Case Study 2: Count the different types of characters

* Requirements: Counts the number of uppercase and lowercase alphabetic characters, number of occurrences of numeric characters, and occurrences of other characters in a string.
* [Email protected]#$%^

     Public Static voidMain (string[] args) {String s= "[Email protected]#$%^"; intBig = 0; intSmall = 0; intnum = 0; intother = 0; //1, gets each character, iterates through a for loop         for(inti = 0; I < s.length (); i++) {            Charc = S.charat (i);//get each character through an index//2, determine if the character is within this range            if(c >= ' A ' && C <= ' Z ') {Big++;//If the content is uppercase, let its corresponding variable increment itself.}Else if(c >= ' a ' && c <= ' z ') {Small++; }Else if(c >= ' 0 ' && C <= ' 9 ') {num++; }Else{ Other++; }        }                //3, print the results of each counterSYSTEM.OUT.PRINTLN (S + "in capital letters:" + big + ", lowercase letters:" + small + ", numeric characters:" + num + ", other characters:" + other + ")); }
conversion function of String

* byte[] GetBytes (): Converts the string to a byte array.
* char[] ToCharArray (): Converts a string to a character array.
* Static string ValueOf (char[] CHS): Turns the character array into a string.
* Static string valueOf (int i): turns data of type int into a string.
* Note: The valueof method of the string class can turn any type of data into a string

* String toLowerCase (): Turns the string into lowercase. Know
* String toUpperCase (): Turns the string into uppercase.
* String concat (String str): Concatenation of strings.

Case Demo

* Requirement: Turn the first letter of a string into uppercase, and the rest to lowercase. (only English uppercase and lowercase characters are considered)

     Public Static void Main (string[] args) {        = "Woaiheimaniaima";         = s.substring (0, 1). toUpperCase (). Concat (s.substring (1). toLowerCase ());        SYSTEM.OUT.PRINTLN (s2);    }
Additional features of the String class

* String replace (char Old,char new)
* String Replace (string old,string new)
* String Trim ()

String inversion

* Requirements: Reverse the string
* Example: Keyboard entry "ABC"
* Output Result: "CBA"

     Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in);//Creating a Keyboard entry objectSystem.out.println ("Please enter a string:"); String Line= Sc.nextline ();//Store keyboard-entered strings in line        Char[] arr = Line.tochararray ();//Convert a string to a character arrayString s = "";  for(inti = arr.length-1; I >= 0; i--) {//backwards traversal of the character arrays = s + arr[i];//Stitching into strings} System.out.println (s); }

Find the number of occurrences of small strings in a large string code implementation

* Count the number of occurrences of a large string of small strings

     Public Static voidMain (string[] args) {//define a large stringString max = "Woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma"; //Defining small stringsString min = "Heima"; //Defining counter Variables        intCount = 0; //Defining Indexes        intindex = 0; //define loops to determine if a small string appears in a large string         while(Index = max.indexof (min))! =-1) {Count++;//counter self-incrementmax = max.substring (index +min.length ());    } System.out.println (count); }

A string of common Java objects

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.