Scanner, String (Java Basics 12)

Source: Internet
Author: User
Tags array to string print object

Introduction to 1.Scanner Overview and methods

* Overview of A:scanner
* is a class entered from the keyboard, has a final decoration, can not be inherited by the quilt class
* Scanner sc = new Scanner (system.in);
* String str = sc.nextline ();
* Construction method Principle of B:scanner
* Scanner (InputStream source)
* There is a static field under the System class:
* public static final inputstream in; The standard input stream, which corresponds to the keyboard entry.

* C: General method
* HASNEXTXXX () to determine if there is a next entry, where xxx can be int,double and so on. If you need to decide whether to include the next string, you can omit xxx.
* NEXTXXX () gets the next entry. The meaning of xxx and the previous method of the same as XXX, by default, scanner use spaces, carriage returns, etc. as separators.

2.Scanner Getting Data

* Two common methods:
* public int Nextint (): Gets a value of type int
* public String nextline (): Gets a value of type string.

Overview of the 3.String class

* A: What is a string
* Overview of the B:string class
* View the description of the string class through the API provided by the JDK
* All string literals (such as "ABC") in a 1.Java program are implemented as instances (objects) of this class.
* 2. Strings are constants, and their values cannot be changed after they are created. A string buffer supports variable strings. Because the String object is immutable, it can be shared.
* The 3.String class includes methods that can be used to examine a single character of a sequence, compare strings, search for strings, extract substrings, create a copy of a string, and convert all characters to uppercase or lowercase.
* The 4.Java language provides special support for string concatenation symbols ("+") and for converting other objects to strings. string concatenation is implemented through the StringBuilder (or StringBuffer) class and its append methods. String conversions are implemented by the ToString method, which is defined by the Object class and can be inherited by all classes in Java.
* 5. Unless otherwise noted, passing a null parameter to a construction method or method in this class throws NullPointerException.

* You can see two words like this.
* A: string literal "abc" can also be seen as a string object.
* String s = "MyWorld";
* B: The string is a constant, and once assigned, it cannot be changed. But it can be made into rubbish.

How to construct a 4.String class

* A: Common construction methods
* 1.public String (): null argument constructed to represent a sequence of empty characters
* 2.public string (byte[] bytes): Convert byte array to string, (also known as decoding)
* 3.public string (byte[] bytes,int index,int length): Turns part of a byte array into a string
* 4.public string (char[] value): Convert character array to string
* 5.public string (char[] Value,int index,int count): Turns a part of a character array into a string
* 6.public String (string original): Convert string constant value to string
* B: Case Demo
* Demonstrates common construction methods of the String class
* "" is the difference from null??
* String s8 = "";
* String S9 = null;
* SYSTEM.OUT.PRINTLN (S8);
* SYSTEM.OUT.PRINTLN (S9);//A reference to a print object returns null if it is NULL, if it is not null
* Returns the ToString method of the object
""--is a string class object that can call all methods in the String class
Null--null is a null value and cannot call any method because the call will report a null pointer exception (NULLPOINTEREXCEPTION)
* public int Length (): Returns the length of this string.

Common face questions for 5.String class

* 1. Determine if S1 and S2 that are defined as string types are equal
* String S1 = "abc";//The object is created in a constant pool, and the address is assigned to S1.
* String s2 = "abc";//See if there are no identical objects in the constant pool, and if so, assign the address to S2, and then recreate the object.
* SYSTEM.OUT.PRINTLN (S1 = = s2);//Compare the address of the object, the same.
* SYSTEM.OUT.PRINTLN (S1.equals (S2));//Compare the value of the object.

* 2. The following sentence creates several objects in memory?
* String S1 = new String ("abc");//creates two objects, one in a constant pool, and one in a heap (a copy of a constant pool).

* 3. Determine if S1 and S2 that are defined as string types are equal
* String S1 = new String ("abc");//Create two objects, where S1 points to the address of the object in the heap,
* String s2 = "abc";//s2 points to the address of the object in the constant pool.
* SYSTEM.OUT.PRINTLN (S1 = = s2);?//Compare address values, in a constant pool, in a heap, are not equal.
* SYSTEM.OUT.PRINTLN (S1.equals (S2));?//comparison is the value of the object, equal.

* 4. Determine if S1 and S2 that are defined as string types are equal
* String S1 = "a" + "B" + "C",//java with constant optimization mechanism, right at compile time, is already "abc" string, so create object in constant pool, then assign address to S1,
* String s2 = "abc";//Find the same object in the constant pool, and if so, assign the object's address value to S2, and if not, create an object in the constant pool and pay the address value to S2.
* SYSTEM.OUT.PRINTLN (S1 = = s2);?//Compare address values, they all point to the same object in the constant pool, so they are equal, the result is true,
* SYSTEM.OUT.PRINTLN (S1.equals (S2));?//The value in the object is compared, equal, and the result is ture.

* 5. Determine if S1 and S2 that are defined as string types are equal
* String S1 = "AB";//Creates an object in a constant pool and assigns its address to S1,
* String s2 = "abc";//Creates an object in a constant pool and assigns its address to S2,
* String s3 = S1 + "C"; When a string is connected to an object with +, the underlying invokes the StringBuffer append method, adds the string, and then converts the StringBuffer object to a String object and assigns a value to S3. The S3 record is the address value of the heap memory object.
* SYSTEM.OUT.PRINTLN (S2 = = s3);? False
* SYSTEM.OUT.PRINTLN (S3.equals (S2));?//ture

The judgment function of the 6.String class

* Boolean equals (Object obj): Compares the contents of a string to the same, in dictionary order, 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.

7.String Class Acquisition function

* 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----Ibid.
* 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.

8. Count 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.  Public Static voidMain (string[] args) {//Defining Counters            intBig = 0;//Uppercase Letters            intSmall = 0; intMath = 0 ; intother = 0; Scanner SC=NewScanner (system.in); System.out.println ("Please enter a string:"); String Str=Sc.nextline ();  for(inti = 0; I < str.length (); i++) {                Chartemp =Str.charat (i); if(Temp >= ' A ' && temp <= ' Z ') {Big++; }Else if(Temp >= ' a ' && temp <= ' z ') {Small++; }Else if(temp >= ' 0 ' && temp <= ' 9 ') {Math++; }Else{ Other++; }} System.out.println ("Capital Letter:" +big); System.out.println ("Lowercase letters:" +small); System.out.println ("Number:" +math); System.out.println ("Illegal characters:" +Other ); }    

Conversion functions for 9.String classes

* byte[] GetBytes (): Converts a string to an array of bytes (also called encoding).
* 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.
* String toUpperCase (): Turns the string into uppercase.
* String concat (String str): Concatenation of strings.

Requirement: The first letter of a string is capitalized and the remainder is lowercase. (only English uppercase and lowercase characters are considered        )  Public Static void Main (string[] args) {            new  Scanner (system.in);            System.out.println ("Please enter a string:");             = sc.nextline ();             =               // chained programming              str1.substring (0, 1). toUpperCase (). Concat (str1.substring (1, Str1.length ()). toLowerCase ());            System.out.println (STR2);        }
requirement: To stitch the data in an array into a string in a specified format*Example:*int[] arr = {}; *Output Result:* "[1, 2, 3]" Public Static voidMain (string[] args) {int[] arr = {A-i};//define an arrayString str = "[";//initializes the value of the string array to "["             for(inti = 0; i < arr.length; i++) {//iterating through an array                if(i = = 2) {//If you traverse to the end, you need to do the processingstr = str + arr[i] + "]"; }Else{//Some of it is the processingstr = str + arr[i] + ","; }} System.out.println (str);//Print a string}

Other features of the 10.String class

* A:string Replacement function and case demonstration
* String replace (char Old,char new)//replace all characters in the string with the old value to the character new value
* String Replace (string old,string new)
* B:string to remove the string two spaces and case demo
* String Trim ()
* C:string Comparison of two strings in dictionary order and demonstration of a case
* int CompareTo (String str) (temporarily not available)
* int comparetoignorecase (String str)

Requirements: Reverse the string* Example: Keyboard input "ABC" * OUTPUT result: "CBA" Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in); System.out.println ("Please enter a string:"); String Str=Sc.nextline (); Char[] arr = Str.tochararray ();//Convert a string into a character array             for(inti = 0; i < ARR.LENGTH/2; i++) {                Chartemp =Arr[i]; Arr[i]= Arr[arr.length-1-i]; Arr[arr.length-1-i] =temp; } String str1= "" ;  for(CharC:arr) {str1= str1 +C;        } System.out.println (STR1); }
Count The number of occurrences of a large string of small strings Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in); System.out.println ("Please enter a larger string:"); String Strbig=Sc.nextline (); System.out.println ("Please enter a smaller string:"); String Strsmall=Sc.nextline (); intCount = 0;//counter            intindex;  while(index = Strbig.indexof (strsmall))! =-1) {Strbig= strbig.substring (index +strsmall.length ()); Count++;        } System.out.println (count); }

Scanner, String (Java Basics 12)

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.