"Java" String class __java

Source: Internet
Author: User
Tags array to string lowercase string indexof

Basic overview of the String class

1, API

Java.lang//No guide pack

Public final class String

string classes represent strings. All string literals In a Java program, such as "ABC", are implemented as instances of this class.

That is, "ABC" is an instance object of the string class.


2. Focus on understanding

The string is a constant, and its value cannot be changed after it is created. Explained as follows:

Screenshot Source: https://www.cnblogs.com/cisum/p/8011485.html


S is just a reference to a string object, not the object itself.


string constant pool:

A string pool is a special store in a method area. When a string is created, it first goes to the string pool and, if found,

Returns a reference to the string directly;

(That is, if the contents of the two strings are exactly the same, then their memory address must be equal and in fact only one)


the security of the thread;

Multithreading is unsafe because multiple child threads manipulate a public variable at the same time, and the value of the variable after the operation

Will change, because string is thread-safe once it has been created and cannot modify its value;

3, create and storage mechanism (written interview book)


4. If you print a reference to the object directly, the ToString method is invoked by default, and the ToString method is overridden if the object is not returned with the @ hash address.

The String class overrides the ToString method and returns the object itself.


Two, the construction method of string class (11 kinds)

1, public string (): empty constructed empty string

2, public string (byte[] bytes): Convert byte array to string, decode GBK byte[]

3, Public String (byte[] bytes,int index, int length): Converts a portion of a byte array to a string, length is the lengths to convert byte[]

4, public string (char[] value): Converts a character array to a string char[]

5, public string (char[] Value,int index, int count): Converts a part of a character array to a string

5, public string (string original): Converts a string constant value to a string


third, common face questions (master)

1, the constant pool does not have this object to create one, and some words directly with no longer create. Address values that point to the same object's reference are the same

2, new String ("abc"); Create two objects, one in the constant pool, one in the heap memory (a copy of the string), and the address value is two objects. (The premise is that there is no ABC before in the constant pool, and if so, an object is created here).

3, "+", the Java language provides special support for string concatenation symbols + and for converting other objects to strings. String-piercing is a concatenation of the Append method that first creates the StringBuilder (StringBuffer) object, and then returns the string through the ToString method.

memory diagram indicating:


flase

true


Iv. the judgment function of String Class (master)

1, Boolean equals (Object obj): Compares the contents of a string to be the same, case-sensitive

2, Boolean equalsignorecase (String str): Comparing the contents of strings are the same, ignoring case

3. Boolean contains (String str): Determining if a large string contains a small string

4. Boolean startwith (String str): Determines whether a string starts with a specified string

5. Boolean endwith (String str): Determines whether a string ends with a specified string

6, 4, Boolean IsEmpty (): Determine whether the character is empty


the difference between null and "":

1, "" is a string constant, the colleague is also a string class object, can also call the String class method

2, NULL is an empty constant, can not invoke any method, otherwise there will be a null pointer exception


v. Simulate user login

Requirements: Simulate landing, give three chances, and hint a few more times.

User name and password are admin

Analysis:

1, analog landing, the need for keyboard input, Scanner

2, give three times the opportunity, need to cycle, for

3, and prompted a few times, need to judge, if

import Java.util.Scanner;;
public class Test_monidenglu {public
	static void Main (string[] args) {		 
		 int count;
		 for (int i = 1;i<=3;i++) {
			 Scanner sc = new Scanner (system.in);
			 System.out.println ("Please enter user name:");
			 String name = Sc.nextline ();
			 System.out.println ("Please enter password:");
			 String password = sc.nextline (); 
			 if (name.equals ("admin") && password.equals ("admin")) {
				 System.out.println ("login successfully.") ");
				 break;
			 else
			 {
				 count = 3-i;
				 System.out.println ("You also have" + Count + "Second Chance");
				 SYSTEM.OUT.PRINTLN ("Please continue to enter");
				 if (count ==0) {
					 System.out.println ("You have run out of times, please contact Customer service to retrieve username and password");}}}


the acquisition function of String Class (master)

1, int length (): Gets the length of the string (the number of each character is not byte length), note that the legth in the array is a property, and here is the method

2, char charAt (int index): Gets the character at the specified index position

3, int indexOf (int ch): Returns the index where the specified character first appears in this string

4, int indexOf (string str): Returns the index where the specified string appears for the first time in this string

5, int indexOf (int ch, int fromindex): Returns the index where the specified character appears for the first time after the specified position in this string

6, LastIndexOf (String str): Returns the index for the last occurrence of the specified string in this string

7, string substring (int start): Intercept a string from the specified location, default to the end

8. String substring (int start,int end): ending the Intercept string from the specified position to the specified position, containing the header without the tail


vii. traversal of strings

Requirements: Traversing strings


Eight, count the number of different types of characters

Requirements: Statistics A string of uppercase characters, lowercase characters, number of occurrences of numeric characters, the number of other characters appear

abcdeabcd123456!@#$%^

public class Test_tongji {public
	static void Main (string[] args) {
		int x = 0, y = 0, z=0, k=0;
		String s = "abcdeabcd123456!@#$%^";
		for (int i = 0;i < S.length (); i++) {
			char a = S.charat (i);  char charAt (int index): Gets the characters of the specified index position
			(a >= ' a ' && a <= ' Z ') {
				x + +;
			} else if (a >= ' a ' && a <= ' z ')
			{
				y++;
			} else if (a >= ' 1 ' && a <= ' 9 ')
			{
				z++;
			} else
			{
				k++;
			}
		}
		System.out.println ("The number of uppercase letters is:" + x);
		System.out.println ("The number of lowercase letters is:" + y);
		System.out.println ("Number of numbers is:" + z);
		System.out.println ("The number of other letters is:" + K);
	}



the conversion function of the string class

1, byte[] geybytes (): Convert a string to a character array encoding: To see the understanding of the conversion of the computer to see

GBK encoding: A Chinese representation of two bytes. The first byte in Chinese is definitely negative.

2, char[] ToCharArray (): Convert string to character array

3. Static string valueof (char[] CHS): Converts a character array to a string

4. Static string valueof (int i): convert data of type int to string

Note: The valueof method of the string class can convert data of any type into a string. Overload type. Are static methods, class names. The method can be invoked. The underlying implementation of this method is actually a method of constructing string, which encapsulates the new string method.

5. String toLowerCase (): Convert string to lowercase

6. String toUpperCase (): Converting strings to uppercase

7. String concat (String str): Stitching strings


X. Other functions of the String class

1. The substitution function of string

String replace (char Old,char new)

String Replace (string old,string new)

2, string to remove both ends of the string space

String trim ();

3. String of two strings in dictionary order compare ASICC Unicode by Code table value

int CompareTo (String str)

int comparetoignorecase (String str): Ignoring case


11, the reversal of the string

Ideas:

1, through the keyboard input to get the string

2. Convert a string into a character array

3, inverted white where the character array. and stitching it again into a string

4, printing

public class Test_fanzhuang {public
	static void Main (string[] args) {
		String s= "abc";
		char[] ch = s.tochararray ();
		String ss = "";
		for (int i = ch.length-1 i >= 0; i--) {   //backwards traverse
			SS = ss + Ch[i];  Character Stitching
		}		
		System.out.println (ss);
	}

12, in the large string to find the number of small string occurrences

Ideas:

1. Define Counter variables

2, the small string to determine whether there is a small string indexOf ()

There, use SUBSTRING () to intercept the large string (in the first small string after the interception), to assign the value to the large string, counter plus 1, continue to loop.

No, return-1

3. Print counter

Import Java.util.Scanner;
public class Test_daxiaochuan {public
	static void Main (string[] args) {
		Scanner SC1 = new Scanner (system.in); 
  
   system.out.println ("Please enter a large string:");
		String S1 = Sc1.nextline ();
		
		Scanner SC2 = new Scanner (system.in);
		System.out.println ("Please enter a small string:");
		String s2 = sc2.nextline ();
		
		int count = 0;
		while (S1.indexof (S2)!=-1) {   //large string occurrence of small string
			int index = s1.indexof (s2);
			S1 = s1.substring (Index+s2.length ());  Intercepting a large string
			count++;
System.out.println (count);
	}
}
  

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.