JavaSE----API之常用类(Object、Scanner、String)

API

4、常用类

4.1 Obejct类

    类 Object 是类层次结构的根类。每个类都使用Object 作为超类。所有对象(包括数组)都实现这个类的方法。

4.1.1 hashCode()方法和getClass()方法

    public int hashCode():返回该对象的哈希码值。哈希值是根据哈希算法计算出来的一个值,这个值和地址值有关,但是不是实际地址值。你可以理解为地址值。

    public final Class getClass():表示此对象运行时类的 Class 对象。

Class类的方法:public String getName():以 String 的形式返回此 Class 对象所表示的实体

    示例:

[java]  view plain  copy
  1. public class StudentDemo {  
  2.     public static void main(String[] args) {  
  3.         Student s1 = new Student();  
  4.         System.out.println(s1.hashCode());  
  5.           
  6.         Student s2 = new Student();  
  7.         System.out.println(s2.hashCode());  
  8.         System.out.println("-----------------");  
  9.           
  10.         Student s = new Student();  
  11.         Class c = s.getClass();  
  12.         String str = c.getName();  
  13.         System.out.println(str);  
  14.           
  15.         //链式编程  
  16.         String str2 = s.getClass().getName();  
  17.         System.out.println(str2);  
  18.     }  
  19. }  
  20. public class Student extends Object{  
  21.       
  22. }  

    运行结果:


4.1.2 toSring()方法

    public String toString():返回该对象的字符串表示。

[java]  view plain  copy
  1. public class StudentDemo {  
  2.     public static void main(String[] args) {  
  3.         Student s = new Student();  
  4.         System.out.println(s.hashCode());  
  5.         System.out.println(s.getClass().getName());  
  6.         System.out.println("--------------------");  
  7.         System.out.println(s.toString());// cn.itcast_02.Student@42552c  
  8.         System.out.println("--------------------");  
  9.         System.out.println(s);  
  10.     }  
  11. }  
  12. public class Student{  
  13.       
  14. }  

    运行结果:


4.1.3 equals(Object obj)方法

    public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。这个方法,默认情况下比较的是地址值。比较地址值一般来说意义不大,所以我们要重写该方法。

    之前我们用过“==”,对于基本数据类型来说,“==”比较的就是值是否相同;对于引用数据类型来说,“==”比较的是地址值是否相同。

[java]  view plain  copy
  1. public class Student {  
  2.     private String name;  
  3.     private int age;  
  4.   
  5.     public Student() {  
  6.         super();  
  7.     }  
  8.   
  9.     public Student(String name, int age) {  
  10.         super();  
  11.         this.name = name;  
  12.         this.age = age;  
  13.     }  
  14. }  
  15. public class StudentDemo {  
  16.     public static void main(String[] args) {  
  17.         Student s1 = new Student("classmate",22);  
  18.         Student s2 = new Student("king"23);  
  19.         Student s3 = new Student("classmate",22);  
  20.         Student s4 = s1;  
  21.         //对引用数据类型来说,“==”比较的是地址值  
  22.         System.out.println(s1 == s2);  
  23.         System.out.println(s1 == s3);  
  24.         System.out.println(s1 == s4);  
  25.         System.out.println("--------------");  
  26.         //equals只能比较引用数据类型  
  27.         System.out.println(s1.equals(s2));  
  28.         System.out.println(s1.equals(s3));  
  29.         System.out.println(s1.equals(s4));  
  30.     }  
  31. }  

    运行结果:



    现在来复写下equals方法。首先要知道String类复写了Object类的equals方法,使得该方法用来比较字面值。

[java]  view plain  copy
  1. public class Student {  
  2.     private String name;  
  3.     private int age;  
  4.   
  5.     public Student() {  
  6.         super();  
  7.     }  
  8.   
  9.     public Student(String name, int age) {  
  10.         super();  
  11.         this.name = name;  
  12.         this.age = age;  
  13.     }  
  14.     @Override  
  15.     public boolean equals(Object obj){  
  16.         if(this == obj){  
  17.             //如果Student类的对象的地址值和传进来的地址值相同,则返回true  
  18.             return true;  
  19.         }  
  20.         //instanceof用来判断该对象名是否是该类名一个对象  
  21.         if(!(obj instanceof Student)){  
  22.             return false;  
  23.         }  
  24.         Student s = (Student)obj;  
  25.         return this.name.equals(s.name) && this.age==s.age;  
  26.     }  
  27. }  

    运行结果:


    注意事项:但是开发时equals还是自动生成

4.1.3 clone()方法

    protected Object clone():创建并返回此对象的一个副本。

    如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出CloneNotSupportedException 异常。所以要clone的对象所属的类一定要实现Cloneable接口。

[java]  view plain  copy
  1. public class StudentDemo {  
  2.     public static void main(String[] args) throws CloneNotSupportedException {  
  3.         //创建学生对象  
  4.         Student s = new Student();  
  5.         s.setName("classmate");  
  6.         s.setAge(22);  
  7.         //克隆学生对象  
  8.         Object obj = s.clone();  
  9.         Student s2 = (Student)obj;  
  10.           
  11.         System.out.println(s.getName()+"---"+s.getAge());  
  12.         System.out.println(s2.getName()+"---"+s2.getAge());  
  13.     }  
  14. }  
  15. public class Student implements Cloneable {  
  16.     private String name;  
  17.     private int age;  
  18.   
  19.   
  20.     public String getName() {  
  21.         return name;  
  22.     }  
  23.   
  24.   
  25.     public void setName(String name) {  
  26.         this.name = name;  
  27.     }  
  28.   
  29.   
  30.     public int getAge() {  
  31.         return age;  
  32.     }  
  33.   
  34.   
  35.     public void setAge(int age) {  
  36.         this.age = age;  
  37.     }  
  38.     @Override  
  39.     protected Object clone() throws CloneNotSupportedException {  
  40.         return super.clone();  
  41.     }  
  42. }  
    运行结果:


4.2 Scanner类

4.2.1 hasNextXxx()方法和NextXxx()方法

    public boolean hasNextXxx():判断键盘所输入的数据是否为Xxx类型,是的话返回true。

    public Xxx nextXxx();将输入信息的下一个标记扫描为一个Xxx类型数据。

[java]  view plain  copy
  1. import java.util.Scanner;  
  2.   
  3. /* 
  4.  *  Scanner:用于接收键盘录入数据 
  5.  *      public boolean hasNextXxx():判断是否是某种类型的元素 
  6.  *      public Xxx nextXxx():获取该元素 
  7.  *   
  8.  *  用int类型数据举例 
  9.  *      public boolean hasNextInt() 
  10.  *      public Int nextInt() 
  11.  */  
  12. public class ScannerDemo {  
  13.     public static void main(String[] args) {  
  14.         //创建对象  
  15.         Scanner sc = new Scanner(System.in);  
  16.         //获取数据  
  17.         if(sc.hasNextInt()){  
  18.             int x = sc.nextInt();  
  19.             System.out.println("x:"+x);  
  20.         }  
  21.         else{  
  22.             System.out.println("您输入的数据有误");  
  23.         }  
  24.     }  
  25. }  

    运行结果:


4.2.2 nextXxx()中两个常用的方法:nextInt()和nextLine()

    public int nextInt():获取一个int类型的值

    public String nextLine():获取一个String类型的值

    需求:先获取一个int类型的数据,再获取一个String类型的数据

[java]  view plain  copy
  1. import java.util.Scanner;  
  2.   
  3. public class ScannerDemo {  
  4.     public static void main(String[] args) {  
  5.         // 创建对象  
  6.         Scanner sc = new Scanner(System.in);  
  7.           
  8.         //先获取一个int类型,再获取一个String类型  
  9.         int a = sc.nextInt();  
  10.         String s = sc.nextLine();  
  11.         System.out.println("a:" + a + ",s:" + s);  
  12.         System.out.println("-----------");  
  13.     }  
  14. }  


    运行结果:


    分析:输入int类型数据5后,按下空格就直接弹出运行结果了,也就是说无法输入字符串类型的数据。

    解决方法:

    1、先获取一个数值后,在创建一个新的键盘录入对象获取字符串。

    2、把所有的数据都先按照字符串获取,然后要什么,你就对应的转换为什么。

    现在使用办法一来实现

[java]  view plain  copy
  1. import java.util.Scanner;  
  2.   
  3. public class ScannerDemo {  
  4.     public static void main(String[] args) {  
  5.         // 创建对象  
  6.         Scanner sc = new Scanner(System.in);  
  7.           
  8.         //先获取一个int类型,再获取一个String类型  
  9.         //int a = sc.nextInt();  
  10.         //String s = sc.nextLine();  
  11.         //System.out.println("a:" + a + ",s:" + s);  
  12.         //System.out.println("-----------");  
  13.           
  14.         int a = sc.nextInt();  
  15.         Scanner sc2 = new Scanner(System.in);  
  16.         String s = sc2.nextLine();  
  17.         System.out.println("a:" + a + ",s:" + s);  
  18.     }  
  19. }  

    运行结果:


4.3 String类

4.3.1 构造方法

    public String():空构造

    public String(byte[] bytes):把字节数组转成字符串

    public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串

    public String(char[] value):把字符数组转成字符串

    public String(char[] value,int index,int count):把字符数组的一部分转成字符串

    public String(String original):把字符串常量值转成字符串

[java]  view plain  copy
  1. public class StringDemo {  
  2.     public static void main(String[] args) {  
  3.         // public String():空构造  
  4.         String s1 = new String();  
  5.         System.out.println("s1:" + s1);  
  6.         System.out.println("s1.length():"+s1.length());  
  7.         System.out.println("-----------------");  
  8.           
  9.         //public String(byte[] bytes):把字节数组转成字符串  
  10.         byte[] bys = new byte[]{97,98,99,100,101};  
  11.         String s2 = new String(bys);  
  12.         System.out.println("s2:" + s2);  
  13.         System.out.println("s2.length():"+s2.length());  
  14.         System.out.println("-----------------");  
  15.           
  16.         //public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串  
  17.         //我想得到字符串“bcd”  
  18.         String s3 = new String(bys,1,3);  
  19.         System.out.println("s3:" + s3);  
  20.         System.out.println("s3.length():"+s3.length());  
  21.         System.out.println("-----------------");  
  22.           
  23.         //public String(char[] value):把字符数组转成字符串  
  24.         char[] chs = new char[]{'a','b','c','d','爱','我'};  
  25.         String s4 = new String(chs);  
  26.         System.out.println("s4:" + s4);  
  27.         System.out.println("s4.length():"+s4.length());  
  28.         System.out.println("-----------------");  
  29.           
  30.         //public String(char[] value,int index,int count):把字符数组的一部分转成字符串  
  31.         String s5 = new String(chs,2,4);  
  32.         System.out.println("s5:" + s5);  
  33.         System.out.println("s5.length():"+s5.length());  
  34.         System.out.println("-----------------");  
  35.           
  36.         //字符串字面值"abc"也可以看成是一个字符串对象。  
  37.         String s7 = "abcde";  
  38.         System.out.println("s7:"+s7);  
  39.         System.out.println("s7.length():"+s7.length());  
  40.     }  
  41. }  

     运行结果:


4.3.2 字符串的特点

    特点:一旦赋值,就不能改变

    怎么理解呢?

[java]  view plain  copy
  1. /* 
  2.  * 字符串特点:一旦赋值,就不能改变。 
  3.  */  
  4. public class StringDemo {  
  5.     public static void main(String[] args) {  
  6.         String s = "hello";  
  7.         s += "world";  
  8.         System.out.println("s:" + s);  
  9.     }  
  10. }  
    运行结果:


    分析:字符串直接赋值的方式是先到字符串常量池里去找,如果有就返回,如果没有就创建并返回。首先将"hello"赋值给字符串的引用s,会现在常量池里找,没有发现,所以创建了“hello”字符串在常量池里,当执行“s += "wrold";”时,会在常量池里创建“world”字符串,然后拼接成一个新的字符串“helloworld”在常量池里,并将地址值返回给引用s。也就是说,”hello“字符串并没有发生改变,只是引用变量s指向了新创建的字符串对象"helloworld"。

    面试题1:

[java]  view plain  copy
  1. public class StringDemo {  
  2.     public static void main(String[] args) {  
  3.         String s1 = "abc";  
  4.         String s2 = "abc";  
  5.         System.out.println(s1 == s2);  
  6.     }  
  7. }  

     运行结果:

    原因分析:字符串创建的时候,有一个字符串常量池,s1创建后,"abc"放入其中。s2创建的时候,"abc"已经存在于字符串常量池中,故引用变量s2直接指向了已经存在的"abc"字符串对象,故s1和s2的地址值相同,故s1==s2。

    面试题2:String s = new String(“hello”)和String s = “hello”有什么的区别?

    前者是在字符串常量池和堆内存中都创建了一个"abc"字符串对象。后者是在字符串常量池中创建了一个"abc"字符串对象。

[java]  view plain  copy
  1. public class StringDemo2 {  
  2.     public static void main(String[] args) {  
  3.         String s1 = new String("hello");  
  4.         String s2 = "hello";  
  5.   
  6.         System.out.println(s1 == s2);  
  7.         System.out.println(s1.equals(s2));  
  8.     }  
  9. }  
    运行结果:


    分析:==:比较引用类型比较的是地址值是否相同。equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。

    面试题3:

[java]  view plain  copy
  1. public class StringDemo4 {  
  2.     public static void main(String[] args) {  
  3.         String s1 = "hello";  
  4.         String s2 = "world";  
  5.         String s3 = "helloworld";  
  6.         System.out.println(s3 == s1 + s2);  
  7.         System.out.println(s3.equals((s1 + s2)));  
  8.   
  9.         System.out.println(s3 == "hello" + "world");   
  10.         System.out.println(s3.equals("hello" + "world"));  
  11.     }  
  12. }   
    运行结果:


    分析原因:为什么第一条输出语句是false,而第三条输出语句是true呢?

    字符串如果是变量相加,先开空间,再拼接,所以第一条输出语句的结果是false;而字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建,所以第三条输出语句的结果是true。

4.3.3 字符串的部分方法

1、判断功能

    boolean equals(Object obj):比较字符串的内容是否相同,区分大小写

    boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写

    boolean contains(String str):判断大字符串中是否包含小字符串

    boolean startsWith(String str):判断字符串是否以某个指定的字符串开头

    boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾

    boolean isEmpty():判断字符串是否为空。

[java]  view plain  copy
  1. public class StringDemo {  
  2.     public static void main(String[] args) {  
  3.         // 创建字符串对象  
  4.         String s1 = "helloworld";  
  5.         String s2 = "helloworld";  
  6.         String s3 = "HelloWorld";  
  7.   
  8.         // boolean equals(Object obj):比较字符串的内容是否相同,区分大小写  
  9.         System.out.println("equals:" + s1.equals(s2));  
  10.         System.out.println("equals:" + s1.equals(s3));  
  11.         System.out.println("-----------------------");  
  12.   
  13.         // boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写  
  14.         System.out.println("equals:" + s1.equalsIgnoreCase(s2));  
  15.         System.out.println("equals:" + s1.equalsIgnoreCase(s3));  
  16.         System.out.println("-----------------------");  
  17.   
  18.         // boolean contains(String str):判断大字符串中是否包含小字符串  
  19.         System.out.println("contains:" + s1.contains("hello"));  
  20.         System.out.println("contains:" + s1.contains("hw"));  
  21.         System.out.println("-----------------------");  
  22.   
  23.         // boolean startsWith(String str):判断字符串是否以某个指定的字符串开头  
  24.         System.out.println("startsWith:" + s1.startsWith("h"));  
  25.         System.out.println("startsWith:" + s1.startsWith("hello"));  
  26.         System.out.println("startsWith:" + s1.startsWith("world"));  
  27.         System.out.println("-----------------------");  
  28.   
  29.         // 练习:boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾这个自己玩  
  30.   
  31.         // boolean isEmpty():判断字符串是否为空。  
  32.         System.out.println("isEmpty:" + s1.isEmpty());  
  33.   
  34.         String s4 = "";  
  35.         String s5 = null;  
  36.         System.out.println("isEmpty:" + s4.isEmpty());  
  37.         // NullPointerException  
  38.         // s5对象都不存在,所以不能调用方法,空指针异常  
  39.         System.out.println("isEmpty:" + s5.isEmpty());  
  40.     }  
  41. }  
    运行结果:


2、获取功能

    int length():获取字符串的长度。

    char charAt(int index):获取指定索引位置的字符。

    int indexOf(int ch): 返回指定字符在此字符串中第一次出现处的索引。为什么这里是int类型,而不是char类型?原因是:'a'和97都可以代表'a',如果定为char类型,只能赋值为'a',如果定为int类型,'a'和97都可以。

    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):从指定位置开始到指定位置结束截取字符串。包含上边界,不包含下边界。[ )

[java]  view plain  copy
  1. public class StringDemo {  
  2.     public static void main(String[] args) {  
  3.         //定义一个字符串  
  4.         String s = "helloworld";  
  5.         //int length():获取字符串长度。  
  6.         System.out.println("s.length():"+s.length());  
  7.         System.out.println("----------------");  
  8.         //char charAt(int index):获取指定索引位置的字符  
  9.         System.out.println("charAt:"+s.charAt(9));  
  10.         System.out.println("----------------");  
  11.         //int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引  
  12.         System.out.println("indexOf:"+s.indexOf('l'));  
  13.         System.out.println("----------------");  
  14.         //int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。  
  15.         System.out.println("indexOf:"+s.indexOf("owo"));  
  16.         System.out.println("----------------");  
  17.         //int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。  
  18.         System.out.println("indexOf:"+s.indexOf('l',4));  
  19.         System.out.println("indexOf:" + s.indexOf('k'4));  
  20.         System.out.println("----------------");  
  21.         //int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。  
  22.           
  23.         //String substring(int start):从指定位置开始截取字符串,默认到末尾。  
  24.         System.out.println("substring:"+s.substring(5));  
  25.         System.out.println("substring:"+s.substring(0));  
  26.         System.out.println("----------------");  
  27.         //String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。  
  28.         //包含上边界,不包含下边界  
  29.         System.out.println("substring:"+s.substring(38));  
  30.         System.out.println("substring:"+s.substring(0,s.length()));  
  31.     }  
  32. }  
    运行结果:


    练习1:遍历获取字符串中的每一个字符(其实也可以先将字符串转为字符数组,然后遍历,这个在转换功能里将)

[java]  view plain  copy
  1. /* 
  2.  * 需求:遍历获取字符串中的每一个字符 
  3.  *  
  4.  * 分析: 
  5.  *      A:如何能够拿到每一个字符呢? 
  6.  *          char charAt(int index) 
  7.  *      B:我怎么知道字符到底有多少个呢? 
  8.  *          int length() 
  9.  */  
  10. public class StringTest {  
  11.     public static void main(String[] args) {  
  12.         String s = "helloworld";  
  13.         for(int x = 0;x < s.length();x++){  
  14.             System.out.print(s.charAt(x));  
  15.         }  
  16.     }  
  17. }  
    运行结果:


    练习2:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

[java]  view plain  copy
  1. /* 
  2.  * 需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符) 
  3.  * 举例: 
  4.  *      "Hello123World" 
  5.  * 结果: 
  6.  *      大写字符:2个 
  7.  *      小写字符:8个 
  8.  *      数字字符:3个 
  9.  *  
  10.  * 分析: 
  11.  *      A:定义一个字符串和三个统计变量 
  12.  *          String s = "Hello123World"           
  13.  *          bigCount=0 
  14.  *          smallCount=0 
  15.  *          numberCount=0 
  16.  *      B:遍历字符串,得到每一个字符。 
  17.  *          length()和charAt()结合 
  18.  *      C:判断该字符到底是属于那种类型的 
  19.  *          char ch = s.charAt(x); 
  20.  *          if(ch>='0' && ch<='9') numberCount++ 
  21.  *          if(ch>='a' && ch<='z') smallCount++ 
  22.  *          if(ch>='A' && ch<='Z') bigCount++ 
  23.  */  
  24. public class StringTest2 {  
  25.     public static void main(String[] args) {  
  26.         String s = "Hello123World";  
  27.         int bigCount = 0;  
  28.         int smallCount = 0;  
  29.         int numberCount = 0;  
  30.   
  31.         for (int x = 0; x < s.length(); x++) {  
  32.             char ch = s.charAt(x);  
  33.             if (ch >= '0' && ch <= '9') {  
  34.                 numberCount++;  
  35.             } else if (ch >= 'a' && ch <= 'z') {  
  36.                 smallCount++;  
  37.             } else if (ch >= 'A' && ch <= 'Z') {  
  38.                 bigCount++;  
  39.             }  
  40.         }  
  41.         System.out.println(numberCount);  
  42.         System.out.println(bigCount);  
  43.         System.out.println(smallCount);  
  44.     }  
  45. }  
    运行结果:


3、转换功能

    byte[] getBytes():把字符串转换为字节数组。

    char[] toCharArray():把字符串转换为字符数组。

    static String valueOf(char[] chs):把字符数组转成字符串。

    static String valueOf(int i):把int类型的数据转成字符串。注意:String类的valueOf方法可以把任意类型的数据转成字符串。

    String toLowerCase():把字符串转成小写。

    String toUpperCase():把字符串转成大写。

    String concat(String str):把字符串拼接。

[java]  view plain  copy
  1. public class StringDemo {  
  2.     public static void main(String[] args) {  
  3.         // 顶一个字符串对象  
  4.         String s = "JavaSE";  
  5.   
  6.         // byte[] getBytes():把字符串转换成字节数组  
  7.         byte[] bys = s.getBytes();  
  8.         for (int x = 0; x < bys.length; x++) {  
  9.             System.out.print(bys[x] + " ");  
  10.         }  
  11.         System.out.println();  
  12.         System.out.println("--------------");  
  13.         // char[] toCharArray():把字符串转换成字符数组  
  14.         char[] chs = s.toCharArray();  
  15.         for (int x = 0; x < chs.length; x++) {  
  16.             System.out.print(chs[x] + " ");  
  17.         }  
  18.         System.out.println();  
  19.         System.out.println("--------------");  
  20.         // static String valueOf(char[] chs):把字符数组转成字符串  
  21.         String ss = String.valueOf(chs);  
  22.         System.out.println(ss);  
  23.         System.out.println();  
  24.         System.out.println("--------------");  
  25.         // static String valueOf(int[] i):把int类型数据转换成字符串  
  26.         int i = 100;  
  27.         String sss = String.valueOf(i);  
  28.         System.out.println(sss);  
  29.         System.out.println("--------------");  
  30.         // String toLowerCase():把字符串转成小写。  
  31.         System.out.println("toLowerCase:" + s.toLowerCase());  
  32.         System.out.println("s:" + s);  
  33.         System.out.println("--------------");  
  34.         // String toUpperCase():把字符串转成大写  
  35.         System.out.println("toUpperCase:" + s.toUpperCase());  
  36.         System.out.println("--------------");  
  37.         // String concat(String str):把字符串拼接  
  38.         String s1 = "hello";  
  39.         String s2 = "world";  
  40.         String s3 = s1 + s2;  
  41.         String s4 = s1.concat(s2);  
  42.         System.out.println("s3:"+s3);  
  43.         System.out.println("s4:"+s4);  
  44.     }  
  45. }  
    运行结果:


    练习:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)

    思路:定义一个字符串,先截取该字符串的第一个字母,然后再截取其他部分。将截取的第一个字母转为大写,截取的其他部分转为小写。最后将两部分拼接起来。

[java]  view plain  copy
  1. public class StringTest {  
  2.     public static void main(String[] args) {  
  3.         //定义一个字符串  
  4.         String s = "helloWORLD";  
  5.         //先获取第一个字符  
  6.         String s1 = s.substring(0,1);  
  7.         String s2 = s.substring(1);  
  8.         String s3 = s1.toUpperCase();  
  9.         String s4 = s2.toLowerCase();  
  10.         String s5 = s3.concat(s4);  
  11.         System.out.println(s5);  
  12.         //优化后的代码  
  13.         //链式编程  
  14.         String result = s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase());  
  15.         System.out.println(result);  
  16.           
  17.     }  
  18. }  
    运行结果:


4、其他功能

    替换功能:

    String replace(char old,char new)

    String replace(String old,String new)

    去除字符串两端空格:

    String trim()

    按字典顺序比较两个字符串:

    int compareTo(String str)

    int compareToIgnoreCase(String str)

[java]  view plain  copy
  1. public class StringDemo {  
  2.     public static void main(String[] args) {  
  3.         //替换功能  
  4.         String s1 = "helloworld";  
  5.         String s2 = s1.replace('l','k');  
  6.         String s3 = s1.replace("owo","ak47");  
  7.         System.out.println("s1:"+s1);  
  8.         System.out.println("s2:"+s2);  
  9.         System.out.println("s3:"+s3);  
  10.           
  11.         //去掉字符串两端空格  
  12.         String s4 = " hello world  ";  
  13.         String s5 = s4.trim();  
  14.         System.out.println("s4:"+s4+"---");  
  15.         System.out.println("s5:"+s5+"---");  
  16.           
  17.         //按字典顺序比较两个字符串  
  18.         String s6 = "hello";  
  19.         String s7 = "hello";  
  20.         String s8 = "abc";  
  21.         String s9 = "xyz";  
  22.         System.out.println(s6.compareTo(s7));  
  23.         System.out.println(s6.compareTo(s8));  
  24.         System.out.println(s6.compareTo(s9));  
  25.     }  
  26. }  
    运行结果:


    练习1:把数组中的数据按照指定格式拼接成一个字符串。例如,将int[] arr = {1,2,3};拼接成一个“[1 2 3]”字符串

[java]  view plain  copy
  1. /* 
  2.  * 需求:把数组中的数据按照指定个格式拼接成一个字符串 
  3.  * 举例: 
  4.  *      int[] arr = {1,2,3};     
  5.  * 输出结果: 
  6.  *      "[1, 2, 3]" 
  7.  * 分析: 
  8.  *      A:定义一个字符串对象,只不过内容为空 
  9.  *      B:先把字符串拼接一个"[" 
  10.  *      C:遍历int数组,得到每一个元素 
  11.  *      D:先判断该元素是否为最后一个 
  12.  *          是:就直接拼接元素和"]" 
  13.  *          不是:就拼接元素和逗号以及空格 
  14.  *      E:输出拼接后的字符串 
  15.  */  
  16. public class StringTest2 {  
  17.     public static void main(String[] args) {  
  18.         int[] arr = {1,2,3};  
  19.         System.out.println(arrayToString(arr));  
  20.     }  
  21.       
  22.     //用功能实现  
  23.     public static String arrayToString(int[] arr){  
  24.         String s = "";  
  25.         s+="{";  
  26.         for(int x = 0;x < arr.length;x++){  
  27.             if(x == arr.length-1){  
  28.                 s+=arr[x];  
  29.                 s+="}";  
  30.             }  
  31.             else{  
  32.                 s+=arr[x];  
  33.                 s+=" ";  
  34.             }  
  35.         }  
  36.         return s;  
  37.     }  
  38. }  
    运行结果:


    练习2:字符串反转。例如,键盘录入“abc”,输出“cba”。

[java]  view plain  copy
  1. /* 
  2.  * 字符串反转 
  3.  * 举例:键盘录入”abc”      
  4.  * 输出结果:”cba” 
  5.  *  
  6.  * 分析: 
  7.  *      A:键盘录入一个字符串 
  8.  *      B:定义一个新字符串 
  9.  *      C:倒着遍历字符串,得到每一个字符 
  10.  *          a:length()和charAt()结合 
  11.  *          b:把字符串转成字符数组 
  12.  *      D:用新字符串把每一个字符拼接起来 
  13.  *      E:输出新串 
  14.  */  
  15. import java.util.Scanner;  
  16.   
  17. public class StringTest3 {  
  18.     public static void main(String[] args) {  
  19.         // 创建对象  
  20.         Scanner sc = new Scanner(System.in);  
  21.         System.out.println("请输入一个字符串:");  
  22.         String s = sc.nextLine();  
  23.         String result = reverseString(s);  
  24.         System.out.println(result);  
  25.         String result2 = reverseString2(s);  
  26.         System.out.println(result2);  
  27.     }  
  28.   
  29.     public static String reverseString(String s) {  
  30.         String str = "";  
  31.         //数组遍历  
  32.         for (int x = s.length() - 1; x >= 0; x--) {  
  33.             str += s.charAt(x);  
  34.         }  
  35.         return str;  
  36.     }  
  37.   
  38.     public static String reverseString2(String s) {  
  39.         String str = "";  
  40.         // 把字符串转成字符数组  
  41.         char[] chs = s.toCharArray();  
  42.         //数组遍历  
  43.         for (int x = chs.length - 1; x >= 0; x--) {  
  44.             str += chs[x];  
  45.         }  
  46.         return str;  
  47.     }  
  48. }  
    运行结果:


    练习3:统计大串中小串出现的次数。例如,统计字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"中“java”出现的次数。

[java]  view plain  copy
  1. /* 
  2.  * 统计大串中小串出现的次数 
  3.  * 举例: 
  4.  *      在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun" 
  5.  * 结果: 
  6.  *      java出现了5次 
  7.  *  
  8.  * 分析: 
  9.  *      前提:是已经知道了大串和小串。 
  10.  *  
  11.  *      A:定义一个统计变量,初始化值是0; 
  12.  *      B:在大串中查找一次小串第一次出现的位置 
  13.  *          a:索引是-1,说明不存在了,返回统计变量 
  14.  *          b:索引不是-1,说明存在,统计变量++ 
  15.  *      C:把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把字符串的值重新赋值给大串 
  16.  *      D:返回B 
  17.  */  
  18. public class StringTest4 {  
  19.     public static void main(String[] args) {  
  20.         //定义大串  
  21.         String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";  
  22.         //定义小串  
  23.         String minString = "java";  
  24.         int count = getCount(maxString,minString);  
  25.         System.out.println(count);  
  26.     }  
  27.     public static int getCount(String maxString,String minString){  
  28.         int count = 0;//定义一个统计变量  
  29.         while(true){  
  30.             int index = maxString.indexOf(minString);//先在大串中查找一次小串第一次出现的位置  
  31.             if(index==-1){//判断  
  32.                 break;  
  33.             }  
  34.             else{  
  35.                 count++;  
  36.             }  
  37.             maxString = maxString.substring(index+minString.length());  
  38.         }  
  39.         return count;  
  40.     }  
  41. }  
    运行结果:


    代码优化:

[java]  view plain  copy
  1. public class StringTest5 {  
  2.     public static void main(String[] args) {  
  3.         String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";  
  4.         String minString = "java";  
  5.         int count = getCount(maxString, minString);  
  6.         System.out.println(count);  
  7.     }  
  8.   
  9.     public static int getCount(String maxString, String minString) {  
  10.         int count = 0;  
  11.         int index = 0;  
  12.         while ((index = maxString.indexOf(minString)) != -1) {  
  13.             count++;  
  14.             maxString = maxString.substring(index + minString.length());  
  15.         }  
  16.         return count;  
  17.     }  
  18. }  
    运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值