Scanner:
By observing the API, it is found that the methods in this class are not modified by static, so to create an object to call, and create an object, we need to learn its construction method.
Construction method:
public Scanner(InputStream source) constructs a new Scanner,
Generates a value scanned from the specified input stream.
The bytes in the stream will be converted to characters using the default charset of the underlying platform.
java uses Unicode by default.
Parameter: InputStream source (InputStream refers to byte stream type)
It is simply understood as the data entered by the keyboard
Overview: it is used to enter data with the keyboard and is used in the program
Scanner(InputStream source)
Because this class is Java Util package, so you need to import the package when you use it in the future.
1. Gets data of type int on the keyboard
nextInt()
2. Get string data
next(): no special characters will be received
nextLine(): special characters, such as line breaks, will be received
public class ScannerDemo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); //Enter data of type int on the keyboard //public int nextInt() scans the next tag entered as int. int i = sc.nextInt(); System.out.println(i); //Enter a string on the keyboard //public String next() finds and returns the next complete token for this scanner. String j = sc.next(); System.out.println(j); //public String nextLine() advances this scanner to the current line and returns skipped input. //nextLine() can receive some special characters, such as newline \ R \ n \ n \ t String s = sc.nextLine(); System.out.println(s); } }
String:
Overview: it is simply understood as a sign that connects many strings
A string is a string of data (character sequence) composed of multiple characters
A string can be thought of as an array of characters******
characteristic:
Once created, the value cannot be changed. The change here means that the character exchange itself in the constant pool cannot be changed
Construction method:
public String()
public String(byte[] bytes)
public String(byte[] bytes,int offset,int length)
public String(char[] value)
public String(char[] value,int offset,int count)
public String(String original)
be careful:
1,String s = new String("hello"); And String s = "hello"; Differences between
new will open up space in heap memory.
2. Problems needing attention when adding strings:
a. If the string is a variable addition, first open up space in the constant pool, and then splice it.
b. If the string is a constant addition, it is added first, and then go to the constant pool to find it. If it is found, it will return. If it is not found, it will open up a new space to store the spliced value.
public class StringDemo1 { public static void main(String[] args) { //public String() String s = new String(); System.out.println(s); //Override the toString() method in the String class //View the length of the string //public int length() returns the length of this string. System.out.println("character string s The length of the is:" + s.length()); //Returns 0 if there are no characters in the string System.out.println("=========================="); //public String(byte[] bytes) / / create a string object based on a byte array byte[] bytes = {99, 98, 66, 56, 77, 41}; String s2 = new String(bytes); System.out.println("s2:" + s2); System.out.println("character string s2 The length of the is:" + s2.length()); System.out.println("=========================="); //public String(byte[] bytes,int index,int length) //Converts a portion of a byte array into a string String s3 = new String(bytes, 1, 3); System.out.println("s3:" + s3); System.out.println("character string s3 The length of the is:" + s3.length()); System.out.println("====================================================="); //public String(char[] value)S //Converts a character array to a string char[] c = {'a', 'b', 'c', 'd', 'I', 'love', 'Feng', 'carry', 'no', 'ah'}; String s4 = new String(c); System.out.println("s4:" + s4); System.out.println("character string s4 The length of the is:" + s4.length()); System.out.println("====================================================="); //public String(char[] value,int index,int length) //Converts a part of a character array into a string String s5 = new String(c, 1, 5); System.out.println("s5:" + s5); System.out.println("character string s5 The length of the is:" + s5.length()); System.out.println("====================================================="); //StringIndexOutOfBoundsException // String s6 = new String(c,4,10); // System.out.println("s6: "+s6); // System.out.println("the length of string s5 is:" + s6.length()); System.out.println("====================================================="); //public String(String original) String s7="Hello"; String s8=new String(s7); System.out.println("s8: "+s8); System.out.println("character string s8 The length of the is:" + s8.length()); } }
A string is a constant whose value cannot be changed after creation
String s = "hello";
s += "world";
What is the value of s?
public class StringDemo2 { public static void main(String[] args) { String s="hello"; s+="world"; System.out.println(s); } }
String s = new String("hello") and string s = "hello"; What's the difference?
String comparison to see the program write results
String splicing to see the program write results
matters needing attention:
1. = = address value when comparing referenced data types
2. The equals method is used in the String class to compare the value of the String, because the equals method is overridden in the String class
public class StringDemo3 { public static void main(String[] args) { String s1=new String("hello"); String s2="hello"; System.out.println(s1==s2); System.out.println(s1.equals(s2)); } }
Look at the program and write the results
public static void main(String[] args) { String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1==s2); System.out.println(s1.equals(s2)); String s3 = new String("hello"); String s4 = "hello"; System.out.println(s3==s4); System.out.println(s3.equals(s4)); String s5 = "hello"; String s6 = "hello"; System.out.println(s5==s6); System.out.println(s5.equals(s6)); } }
1. If the string is a variable addition, first open up space in the constant pool, and then splice it.
2. If the string is a constant addition, it is added first, and then go to the constant pool to find it. If it is found, it will return. If it is not found, it will open up a new space to store the spliced value.
public class StringDemo5 { public static void main(String[] args) { String s1="hello"; String s2="world"; String s3="helloworld"; String s4="hello"+"world"; System.out.println(s3==s4); String s5=s1+s2; System.out.println(s3==s5); System.out.println(s3==(s1+s2)); System.out.println(s3.equals(s1+s2)); } }
Judgment function of String class:
boolean equals(Object obj)
boolean equalsIgnoreCase(String str)
boolean contains(String str)
boolean startsWith(String str)
boolean endsWith(String str)
boolean isEmpty()
Note: String s = ""; And String s = null; Precautions for comparing strings to avoid null pointer exceptions
public class StringDemo6 { public static void main(String[] args) { String s1="helloWorld"; String s2="HelloWorld"; String s3="HelloWorld"; //boolean equals(Object obj) compares whether the contents in the string are the same and is case sensitive System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println("============================="); //boolean equalsIgnoreCase(String str) compares whether the contents in the string are the same, ignoring case System.out.println(s1.equalsIgnoreCase(s2)); System.out.println(s1.equalsIgnoreCase(s3)); System.out.println("============================="); //boolean contains(String str) //Judge whether a large string contains a small string. If so, return true; otherwise, return false //Case sensitive System.out.println(s1.contains("Hello")); System.out.println(s1.contains("hel")); System.out.println(s1.contains("owo")); System.out.println("============================="); //boolean startsWith(String str) //Tests whether this string starts with the specified string //Case sensitive System.out.println(s1.startsWith("hel")); System.out.println(s1.startsWith("Hel")); System.out.println(s1.startsWith("hel34")); System.out.println("============================="); //boolean endsWith(String str) //Tests whether this string ends with the specified string //Case sensitive System.out.println(s1.endsWith("rld")); System.out.println(s1.endsWith("rlD")); System.out.println("============================="); //boolean isEmpty() //Determine whether the string is an empty string String s4=""; String s5=null; System.out.println(s4==s5); System.out.println(s5==s4); System.out.println(s4.equals(s5)); //System. out. println(s5.equals(s4)); // Null pointerexception error /** * Note: in the future, NullPointerException null pointer exception is likely to occur when comparing the contents of strings * The variable that previously called the method may be null * So in the future, in order to avoid such problems, if it is variable 1 In the case of equals (variable 2), judge whether the variable 1 is null before doing equals * When comparing the equals of a variable 1 with the String constant 1, put the String constant 1 first and call the method, because we said that a single String is also a String object * */ //Requirement: compare whether the value of s6 is the same as that of s7 String s6=null; String s7="hello"; if (s6!=null){ if (s6.equals(s7)){ System.out.println("It's the same"); }else { System.out.println("s6 yes null value"); } //Requirement 2: judge whether the value of s6 is hello if ("hello".equals(s6)){ System.out.println("It's the same"); }else { System.out.println("s6 The value of is not hello"); } } } }
Get function of String class:
int length()
char charAt(int index)
int indexOf(int ch)
int indexOf(String str)
int indexOf(int ch,int fromIndex)
int indexOf(String str,int fromIndex)
String substring(int start)
String substring(int start,int end)
/* String Class: int length() char charAt(int index) int indexOf(int ch) int indexOf(String str) int indexOf(int ch,int fromIndex) int indexOf(String str,int fromIndex) String substring(int start) String substring(int start,int end) */ public class StringDemo7 { public static void main(String[] args) { String s="helloworld"; //int length() gets the length of the string System.out.println("The length of the string is:"+s.length()); System.out.println("==========================="); //char charAt(int index) returns the character at the specified index //0<=index<=length()-1 System.out.println(s.charAt(4)); System.out.println(s.charAt(0)); // System. out. println(s.charAt(100));// Error in stringindexoutofboundsexception System.out.println(s.charAt(9)); System.out.println("==========================="); //public int indexOf(int ch) returns the index within the string where the specified character first appears. //Requirement: get the position where o first appears in the string System.out.println(s.indexOf('o')); System.out.println(s.indexOf(97)); //If there are no such characters in this string, - 1 is returned. System.out.println("==========================="); //public int indexOf(String str) returns the index in the string where the specified substring first appears. //Returns the index position where the first character of a small string appears in a large string //owo System.out.println(s.indexOf("owo")); //If there is no small string in the large string, - 1 is returned System.out.println(s.indexOf("owe")); System.out.println(s.indexOf("qwer")); System.out.println("==========================="); // public int indexOf(int ch,int fromIndex) // Returns the index within the string where the specified character first appears, and starts the search with the specified index. //If found, the index of the character in the whole string is returned System.out.println(s.indexOf("i",4)); System.out.println(s.indexOf("i",1000)); System.out.println(s.indexOf("i",4)); System.out.println(s.indexOf("i",1000)); System.out.println("=================================="); // int indexOf(String str,int fromIndex) System.out.println("=================================="); //helloworld //String substring(int start) intercepts the string from the specified position, including the position where the interception starts, and intercepts to the end //If the given index value does not exist, an error is reported System.out.println(s.substring(3)); // loworld // System.out.println(s.substring(100)); // StringIndexOutOfBoundsException System.out.println("=================================="); //String substring(int start,int end) //Intercept part of the string //The intercepted string starts at the start position and ends at the end-1 position //Left closed right open [,) including head but not tail. System.out.println(s.substring(5,8)); // wor // System.out.println(s.substring(1,20)); //StringIndexOutOfBoundsException } }
Conversion function of String class:
byte[] getBytes()
char[] toCharArray()
static String valueOf(char[] chs)
static String valueOf(int i)
String toLowerCase()
String toUpperCase()
String concat(String str)
public String[] split(String regex) **********
import java.nio.charset.StandardCharsets; import java.util.Locale; /*String Class conversion function: // byte[] getBytes() // char[] toCharArray() //static String valueOf(char[] chs) //static String valueOf(int i) // String toLowerCase() // String toUpperCase() // String concat(String str) //public String[] split(String regex) ********** */ public class StringDemo8 { public static void main(String[] args) { String s = "HelloWorLD"; //public byte[] getBytes() encodes this String as a byte sequence using the default character set of the platform, and stores the result in a new byte array. //Convert string to byte array byte[] bytes = s.getBytes(StandardCharsets.UTF_8); // System.out.println(bytes); for (int i = 0; i < bytes.length; i++) { System.out.print(bytes[i] + "\t"); } System.out.println(); System.out.println("==============================="); //char[] toCharArray() //Convert string to character array char[] chars = s.toCharArray(); for (int j = 0; j < bytes.length; j++) { System.out.print(chars[j]); } System.out.println(); System.out.println("================================="); //static String valueOf(char[] chs) //Convert character array to string String s1 = String.valueOf(chars); System.out.println(s1); System.out.println("=============================="); //static String valueOf(int i) database //Converts data of type int to a string String s2 = String.valueOf(100);// 100 --> "100" System.out.println(s2); System.out.println("=============================="); //String toLowerCase() //Convert all contents of the string to lowercase String s3 = s.toLowerCase(Locale.ROOT); System.out.println(s3); System.out.println("=============================="); //String toUpperCase() converts all contents in the string to uppercase String s4 = s.toUpperCase(); System.out.println(s4); System.out.println("=============================="); //String concat(String str) //Splice the str string in parentheses to the end of the big string String s5 = s.concat("hadoop"); System.out.println(s5); System.out.println("=============================="); //public String[] split(String s) String s6 = "hello world hello java world"; //Requirement: find each word in the string String[] strings = s6.split(""); for (int j = 0; j < strings.length; j++) { System.out.print(strings[j]); } } }
Other functions of String class:
Replacement function
String replace(char old,char new)
String replace(String old,String new)
Remove several spaces around the string
String trim()
Compare whether the contents of the two strings are the same in dictionary order, which involves source code analysis
int compareTo(String str)
int compareToIgnoreCase(String str)
/* String Other functions of class: Replace function String replace(char old,char new) String replace(String old,String new) Remove two spaces in the string String trim() Compares two strings in dictionary order int compareTo(String str) int compareToIgnoreCase(String str) */ public class StringDemo9 { public static void main(String[] args) { String s = "hellowrodldajavahadoopowollohelloowo"; //String replace(char old,char new) //Replaces the new string with all characters specified in the string and returns a replaced string String s1 = s.replace('l', 'q'); System.out.println(s); System.out.println(s1); System.out.println("=================================="); //String replace(String old,String new) //Replace the small string in the string with a new small string and return a replaced string String s2=s.replace("owo","==="); System.out.println(s); System.out.println(s2); System.out.println(); //What happens if the replaced string does not exist? The original string is returned String s3=s.replace("qwer","LOL"); System.out.println(s); System.out.println(s3); System.out.println("=================================="); //String trim() removes several spaces on both sides of the string String s5=" HelloWorld "; System.out.println(s5); System.out.println(s5.trim()); System.out.println("=================================="); //int compareTo(String str) / / compare whether the strings are the same. If they are the same, 0 is returned String s6="hello";// The ASCII value of h is 104 String s7="hello"; String s8="abc";// The ASCII value of a is 97 String s9="qwe"; // The ASCII value of q is 113 System.out.println(s6.compareTo(s7));// 0 System.out.println(s6.compareTo(s8));// 7 System.out.println(s6.compareTo(s9)); // -9 String s10="hel"; System.out.println(s6.compareTo(s10));//2 } }
1: Traversal gets each character in the string
2: Count the occurrence times of uppercase, lowercase and numeric characters in a string. (other characters are not considered)
/* 1: Traversal gets each character in the string 2: Count the occurrence times of uppercase, lowercase and numeric characters in a string. (other characters are not considered) */ public class StringTest1 { public static void main(String[] args) { String s = "javaMySqlHadoopHive12138"; //Traversal gets each character in the string //Convert string to character array char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { System.out.print(chars[i]); } System.out.println(); System.out.println("==================================="); //Count the occurrence times of uppercase, lowercase and numeric characters in a string. (other characters are not considered) //1. Define three variables and count three results int bigCount = 0; int smallCount = 0; int numberCount = 0; //2. Traverse the character array to get each character and judge which class each character belongs to for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c >= 'A' && c <= 'Z') { bigCount++; } else if (c >= 'a' && c <= 'z') { smallCount++; } else if (c >= '0' && c <= '9') { numberCount++; } } System.out.println("The number of uppercase characters is:" + bigCount); System.out.println("The number of lowercase characters is:" + smallCount); System.out.println("The number of numeric characters is:" + numberCount); } }
Convert the first letter of a string to uppercase and the rest to lowercase. (only English uppercase and lowercase characters are considered)
For example: "Hadoop Java" - > "Hadoop Java"
1. Convert all to lowercase
2. Gets the first character to uppercase
Specific implementation:
1. Intercept the first character and other characters
2. First character to uppercase
3. Convert other characters to lowercase
4. Splicing
import java.util.Locale; public class StringTest2 { public static void main(String[] args) { String s = "hADoopJava"; System.out.println("Before conversion" + s); //Converts all characters in a string to lowercase String s1 = s.toLowerCase(); //Get first character // char s2=s1.charAt(0); String s2 = s1.substring(0, 1); // Convert first character to uppercase String s3 = s2.toUpperCase(); //Gets characters other than the first character String s4=s1.substring(1); //Splice the capitalized characters with the rest of the characters String result=s3.concat(s4); System.out.println("After conversion:"+result); System.out.println("============Conversion by chain programming=============="); String result2=s.substring(0,1) .toUpperCase(Locale.ROOT) .concat(s.substring(1).toLowerCase()); System.out.println("After conversion:"+result2); } }
/*
Concatenate the data in the array into a string according to the specified format
Example: int[] arr = {1,2,3}; Output result: [1, 2, 3]
*/
public class StringTest3 { public static void main(String[] args) { int[] arr={1,2,3}; String s=""; for (int i=0;i< arr.length;i++){ String s1 = String.valueOf(arr[i]); if(i==0){ System.out.print(s.concat("[").concat(s1).concat(",")); }else if(i==arr.length-1){ System.out.print(s.concat(s1).concat("]")); }else { System.out.print(s.concat(s1).concat(",")); } } System.out.println(s); } }
String inversion
For example: keyboard input "abc" output result: "cba"
analysis:
1. Import package and create keyboard entry object
2. Create an empty string
3. Convert string to character array
4. Traverse backwards to get each character
5. Splice the characters obtained each time
6. Output
/* String inversion For example, enter "abc" on the keyboard Output result: "cba" analysis: 1,Import package and create keyboard entry object 2,Create an empty string 3,Convert string to character array 4,Traverse backwards to get each character 5,Splice the characters obtained each time 6,output */ import java.util.Scanner; public class StringTest4 { public static void main(String[] args) { //Create keyboard entry object Scanner sc = new Scanner(System.in); System.out.println("Please enter a string:"); String s = sc.next(); //Create an empty string String s1 = ""; //Convert string to character array char[] chars = s.toCharArray(); //Traverse backwards to get each character for (int i = chars.length - 1; i >= 0; i--) { //Convert each character to a string String s2 = String.valueOf(chars[i]); // System.out.println(s2); //Splice the characters obtained each time s1 = s1.concat(s2); } System.out.println("The inverted string is:" + s1); } }
Count the number of occurrences of large and small strings
For example: in the string "woaijavawozhenaijavawozhenaijavawozhenaijavaxinbuxinwoaijavagundasdqwdeqwdasvgwrefas javajijavawozhenaijavawozhenaijavaxinbuxinwozhenaijavagundaijavawozhenaijavaxinbuxinwoaijavagundaijavawozhenaijavawozhenaix inbuxinwoaijavagundaijavawozhenaijavawozhenaijavax inbuxinwoaijavagundaijavawozhenaijavawozhenaijavaxinbuxinbuaij avagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagunda”
How many times does java appear in
public class StringTest5 { public static void main(String[] args) { //Create a string String bigString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundasdqwdeqwdwdasvgwrefasjavajavajijijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagundaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagunda"; //Define the small string to find: java String minString = "java"; //Define a variable to count the number of occurrences of a small string int count = 0; //Find the position where the small string first appears in the large string int index = bigString.indexOf(minString); //It's also possible that I didn't find it the first time if (index == -1) { System.out.println("There is no small string in the large string" + minString); } else { while (index != -1) { count++; //Intercept string int startIndex = index + minString.length(); bigString = bigString.substring(startIndex); //Continue to find the location index of the small string index = bigString.indexOf(minString); System.out.println("The small string is found, and the intercepted large string is:"+bigString); } } System.out.println("======================================================"); System.out.println(minString + "In big string" + bigString + "The number of occurrences in is:" + count); } }