JAVA API ---- Scanner类 与 String类

JAVA API — Scanner类 与 String类

Scanner类

  • 概述:JDK5以后用于获取用户的键盘输入。

  • 构造方法原理:
    Scanner(InputStream source)
    System类下有一个静态的字段:public static final InputStream in; 标准的输入流,对应着键盘录入。

  • 读取输入:

    要想通过控制台进行输入,首先需要构造一个Scanner对象,并与“标准输入流”System.in关联。Scanner in = new Scanner(Systeam.in);

Scanner类的hasNextXxx()和nextXxx()方法:

  • 基本格式:
    hasNextXxx(): 判断下一个是否是某种类型的元素,其中Xxx可以是Int,Double等。
    如果需要判断是否包含下一个字符串,则可以省略Xxx
    nextXxx(): 获取下一个输入项。Xxx的含义和上个方法中的Xxx相同

  • 案例演示:
    演示结合判断获取数据的情况

    public class ScannerDemo {
        public static void main(String[] args) {     
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入一个字符串");
            String s = scanner.nextLine();    //获取输入的字符串
               //scanner.nextDouble();    //获取输入的浮点数
               //scanner.nextInt();
               //scanner.nextLong();    
            System.out.println("你输入的是:  "+s);
        }
    }
    

Scanner获取数据出现的小问题:

  • 两个常用的方法:
    public int nextInt():获取一个int类型的值
    public String nextLine():获取一个String类型的值
    public String next():获取一个String类型的值

  • 案例演示:

    先获取int值,然后获取String值出现问题。

    public class ScannerDemo2 {
        public static void main(String[] args) {       
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个整数");
            int num = sc.nextInt();
            System.out.println("你输入的数字是:"+num);
            
            System.out.println("请输入一个字符串");
            String s = sc.nextLine();     
            System.out.println("你输入的字符串是:"+s);
        }
    }
    
    请输入一个整数
    1
    你输入的数字是:1
    请输入一个字符串
    你输入的字符串是:
    
    • 出现问题:当使用Scanner先录入整数后,再用nextLine()录入字符串时,你会发现,并没有输入字符串就结束了?
      原因: 其实系统把你上次敲的回车换行符,已经录入了。nextLine()录入字符串时包含回车键。

    • 解决办法1: 可以在录入字符串的时候,用next(),next()录入的字符串不包含回车键

      public class ScannerDemo2 {
          public static void main(String[] args) {        
              Scanner sc = new Scanner(System.in);
              System.out.println("请输入一个整数");
              int num = sc.nextInt();
              System.out.println("你输入的数字是:"+num);
             
              System.out.println("请输入一个字符串");
              //String s = sc.nextLine();
              String s = sc.next();
              System.out.println("你输入的字符串是:"+s);
          }
      }
      
      请输入一个整数
      2
      你输入的数字是:2
      请输入一个字符串
      ajdjhf
      你输入的字符串是:ajdjhf
      
    • 解决办法2:先获取一个数值后,再创建一个新的键盘录入对象获取字符串。

      public class ScannerDemo2 {
          public static void main(String[] args) {       
              Scanner sc = new Scanner(System.in);
              System.out.println("请输入一个整数");
              int num = sc.nextInt();
              System.out.println("你输入的数字是:"+num);
              
              sc=new Scanner(System.in);
              System.out.println("请输入一个字符串");
              String s = sc.nextLine();
              System.out.println("你输入的字符串是:"+s);
          }
      }
      
      请输入一个整数
      3
      你输入的数字是:3
      请输入一个字符串
      ghdnkydb
      你输入的字符串是:ghdnkydb
      
  • 案例演示:nextLine()和next()录入字符串时遇到空格的处理

    public class ScannerDemo3 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个字符串");
            String s = sc.nextLine();   //录入的字符串中,包含空格
            System.out.println(s);
        }
    }
    
    请输入一个字符串
    sudhsdcjjh  ncwkhiuwech
    sudhsdcjjh  ncwkhiuwech
    
    public class ScannerDemo3 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个字符串");       
            String s=sc.next();    //录入的字符串中,遇到第一个空格后,空格后面的内容就不录入
            System.out.println(s);
        }
    }
    
    请输入一个字符串
    khkjdhujs  xksjdiwjij
    khkjdhujs
    

String类

  • 字符串:
    字符串是由多个字符组成的一串数据(字符序列)。字符串可以看成是字符数组。

  • String类:

    通过JDK提供的API,查看String类的说明可以看到这样的两句话。
    a:Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。
    b:字符串是常量,一旦被创建,就不能被改变。

String类的构造方法:

  • 常见构造方法:
    public String() : 空构造,初始化一个新创建的 String 对象,使其表示一个空字符序列。
    public String(byte[] bytes) : 把字节数组转成字符串
    public String(byte[] bytes,int index,int length) : 把字节数组的一部分转成字符串(index:表示的是从第几个索引开始, length表示的是长度)
    public String(char[] value) : 把字符数组转成字符串
    public String(char[] value,int index,int count) :把字符数组的一部分转成字符串
    public String(String original) :把字符串常量值转成字符串

    public int length():返回此字符串的长度。

  • 案例演示1:

    public class MyTest {
        public static void main(String[] args) {        
            //创建一个空的字符串对象
            String s = new String(); 
            System.out.println(s.toString());
            
            String s1 = new String("abcfshh");
            System.out.println(s1.toString());  //字符串重写了toString方法,打印的是字符串的内容
            
            //字符串可以看做是一个长度固定的有序字符序列,每个组成的字符编有索引从0开始  
            int length = s1.length(); //获取字符串的长度
            System.out.println(length);
        }
    }
    
    
    abcfshh
    7
    
  • 案例演示2:

    public class MyTest3 {
        public static void main(String[] args) {
            定义字符串的两种方式
            String s = new String("abc");
            String str="ccc";    //所有字符串字面值(如 "abc" )都作为String类的实例实现。
            
            //字符串是常量;它们的值在创建之后不能更改。
            String s1 = "hello" ;
            s1 =  "world" + "java";
            System.out.println(s1);   //worldjava
        }
    }
    
    • 字符串的内存图:字符串存储在方法区的常量池中。

    在这里插入图片描述
    字符串一旦被创建之后就不能更改,指的是字符串的值不能改变,而引用变量可以改变。

  • 字符串两种定义方式的区别:

    public class MyTest {
        public static void main(String[] args) {
            String s1 = new String("hello");
            String s2 = new String("hello");
            System.out.println(s1 == s2);   //false
            System.out.println(s1.equals(s2));   //true
    
            String s3 = new String("hello");
            String s4 = "hello";
            System.out.println(s3 == s4);     //false
            System.out.println(s3.equals(s4));   //true
    
            String s5 = "hello";
            String s6 = "hello";
            System.out.println(s5 == s6);  //true
            System.out.println(s5.equals(s6));   //true
        }
    }
    
    • 内存图:
      在这里插入图片描述
  • 案例演示3:常用的构造方法

    public class StringDemo {
        public static void main(String[] args) {      
            byte[] bytes={97,98,99,100};
            //将字节数组,转换成字符串
            String s = new String(bytes); // abcd
            //将字节数组的一部分转成字符串
            //StringIndexOutOfBoundsException 字符串索引越界异常
            s=new String(bytes,2,2);
            System.out.println(s);   //cd
    
            char[] chas={'a','b','c','你','好',100};
            //将字符数组转换成字符串
            String s1 = new String(chas);
            //将字符数组的一部分转成字符串
            s1=new String(chas,3,); //从3索引处开始,转2个字符
            System.out.println(s1);   //你好 
        }
    }
    

String类的判断功能:

  • String类的判断功能
    public boolean equals(Object obj): 比较字符串的内容是否相同,区分大小写
    public boolean equalsIgnoreCase(String str): 比较字符串的内容是否相同,忽略大小写
    public boolean contains(String str): 判断字符串中是否包含传递进来的字符串
    public boolean startsWith(String str): 判断字符串是否以传递进来的字符串开头
    public boolean endsWith(String str): 判断字符串是否以传递进来的字符串结尾
    public boolean isEmpty(): 判断字符串的内容是否为空串""。

  • 案例演示:String类的判断功能

    public class StringDemo2 {
        public static void main(String[] args) {
        	//比较字符串的内容是否相同
            boolean b = "abc".equals("ABC");  //false
            b="abc".equalsIgnoreCase("ABC");  //true
          
    		//判断字符串中是否包含传递进来的字符串
            boolean b1 = "像我这样优秀的人,本该灿烂过一生".contains("灿烂");
            System.out.println(b1);    //true
    
            //判断一个字符串,是否以某个字符串结尾
            boolean b2 = "139 9909 9098".endsWith("9098");
            System.out.println(b2);    //true
    
            //"判断一个字符串是不是以某个字符串开头"
            boolean b3 = "王百万".startsWith("王");
            System.out.println(b3);    //true
    
    
            boolean b4 = " ".length() == 0 ? true : false;
            System.out.println(b4);     //false
    
            //判断空串的
            boolean empty = "".isEmpty();
            System.out.println(empty);    //true
        }
    }
    

String类的获取功能:

  • String类的获取功能
    public int length(): 获取字符串的长度。
    public char charAt(int index): 获取指定索引位置的字符
    public int indexOf(int ch): 返回指定字符在此字符串中第一次出现处的索引。
    public int indexOf(String str): 返回指定字符串在此字符串中第一次出现处的索引。
    public int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
    public int indexOf(String str,int fromIndex): 返回指定字符串在此字符串中从指定位置后第一次出现处的索引。可以顺带提一下lastIndexOf系列
    public String substring(int start): 从指定位置开始截取字符串,默认到末尾。
    public String substring(int start,int end): 从指定位置开始到指定位置结束截取字符串。

  • 案例演示: String类的获取功能

    public class StringDemo {
        public static void main(String[] args) {        
            //字符串有索引,根据索引截取单个字符
            String s = "七月的风,八月的雨";
            char ch = s.charAt(s.length() - 1);
            System.out.println(ch);    //雨
    
            //查找这个字符串中某个字符第一次出现的索引
            String str = "几次真的想让自己醉,让自己远离哪些恩怨是非";
            int index = str.indexOf('自');
            System.out.println(index);    //6
            char charat = str.charAt(str.indexOf('自'));
            System.out.println(charat);    //自
            //如果没有找到,返回 -1 经常用这个返回值判断
            int of = str.indexOf("自己醉1");
            System.out.println(of);    //-1
    
            //从指定的位置开始找,找某个字符第一次出现的索引
            int indexOf = str.indexOf('自', 7);
            
            //从指定的位置开始找,找某个字符串第一次出现的索引
            int indexOf = str.indexOf("恩怨是非", str.indexOf('自') + 1);
            System.out.println(indexOf);
            
            //倒着查找,找某个字符第一次出现的索引
            int i = str.lastIndexOf('自', 10);   //6
            System.out.println(i);
            
            //从指定索引处截取到末尾,返回的是截取到的字符串
            String str2 = "几次真的想让自己醉,让自己远离哪些恩怨是非";
            String s1 = str2.substring(6); 
            System.out.println(s1);   //自己醉,让自己远离哪些恩怨是非
    
            String s2 = str2.substring(0, 9); //含头不含尾 几次真的想让自己醉
            s2 = str2.substring(0, str.indexOf('醉') + 1); //含头不含尾
            System.out.println(s2);    //几次真的想让自己醉
        }
    }
    
字符串的遍历:
public class StringDemo2 {
    public static void main(String[] args) {
        //遍历字符串
        String str = "几次真的想让自己醉";
        
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
        }
     }
}
统计字符串中不同类型字符个数:

案例演示: 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

public class StringDemo3 {
    public static void main(String[] args) {  
        String str = "AFDFDdfdfdfAFDFd2113232safsdfsdf0000asdfasdfAA";
        //定义三个统计遍历
        int da = 0;
        int xiao = 0;
        int num = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch >= 'a' && ch <= 'z') {
                xiao++;
            } else if (ch >= 'A' && ch <= 'Z') {
                da++;
            } else if (ch >= '0' && ch <= '9') {
                num++;
            }
        }
        System.out.println("大写字母有"+da+"个");
        System.out.println("小写字母有" + xiao + "个");
        System.out.println("数字字符有"+num+"个");
    }
}

String类的转换功能:

  • String的转换功能:
    public byte[] getBytes(): 把字符串转换为字节数组。
    public char[] toCharArray(): 把字符串转换为字符数组。
    public static String valueOf(char[] chs): 把字符数组转成字符串。
    public static String valueOf(int i): 把int类型的数据转成字符串。
    注意:String类的valueOf方法可以把任意类型的数据转成字符串。
    public String toLowerCase(): 把字符串转成小写。
    public String toUpperCase(): 把字符串转成大写。
    public String concat(String str): 把字符串拼接。

  • 案例演示1:把字符串转换为字节数组

    public class MyTest {
        public static void main(String[] args) {       
            //把字节数组转成字符串
            String s = new String(new byte[]{100, 127},0,1);
            System.out.println(s);    //df
            
            //把字符串转换为字节数组
        	byte[] bytes = "abcd".getBytes();
        	for (int i = 0; i < bytes.length; i++) {
            	System.out.println(bytes[i]);  //97 98 99 100
        	}
    
      	 	System.out.println(new String(bytes));   //abcd      
    
        	byte[] bytes1 = "你好啊".getBytes();
        	System.out.println(bytes1.length);    //9
    
        	for (int i = 0; i < bytes1.length; i++) {
            	System.out.println(bytes1[i]);
       		 }
    
        	System.out.println(new String(bytes1));   //你好啊
    	}
    }      
    
  • 案例演示2:把字符串转换成字符数组

    public class MyTest2 {
        public static void main(String[] args) {
            //把字符数组转换成字符串
            String s = new String(new char[]{'a', 'b', 'c'},0,2);
            System.out.println(s);   //ab
    
    		//把字符串转换成字符数组
            String str="上课不要玩王者荣耀";
            char[] chars = str.toCharArray();
             
            //char[] chas=new char[str.length()];
            //for (int i = 0; i < str.length(); i++) {
            //    char c = str.charAt(i);
            //    chas[i]=c;
            //}
            //       
           
            //for (char c : chars) {
            //    System.out.println(c);
            //}
            
            //转换大小写
            String s1 = "abcd".toUpperCase();
            System.out.println(s1);   //ABCD
    
            String s2 = "ABCD".toLowerCase();  
            System.out.println(s2);     //abcd
        }
    }
    
  • 案例演示3: 把任意类型转换成字符串,与拼接字符串

    public class MyTest3 {
        public static void main(String[] args) {
            //把数字转换成字符串
            int num = 100;
            String str = num + ""; //"100"
    
            boolean b = false;
            String str2 = b + ""; //"false"
    
            //把任意类型转换成字符串
            String s = String.valueOf(100);
            String s1 = String.valueOf(new char[]{'a', 'b'});
            String s2 = new String(new char[]{'a', 'b'});
            String s3 = String.valueOf(new Object());
            System.out.println(s3);
    
            String str3="abc"+"ccc"+"ddd";
    
            //concat("ccc") 拼接字符串,可以替代加号
            String concat = "abc".concat("ccc").concat("aaaa").concat("abbc");
            System.out.println(concat);
            "abc".concat("");
        }
    }
    
  • 案例演示4:字符串大小写转换

    public class MyTest4 {
        public static void main(String[] args) {     
            //需求:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)
            String str="aAFSDFDfdfadfasdfasdfasfdasdfasdf";
            String s =str.substring(0,1).toUpperCase().concat(str.substring(1).toLowerCase());
            System.out.println(s);      
        }

String类的其他功能:

  • String的替换功能:

    public String replace(char old,char new): 将指定字符进行互换
    public String replace(String old,String new): 将指定字符串进行互换

  • String的去除字符串两空格:
    public String trim(): 去除两端空格

  • String的按字典顺序比较两个字符串:
    public int compareTo(String str): 会对照ASCII 码表 从第一个字母进行减法运算, 返回的就是这个减法的结果。如果前面几个字母一样会根据两个字符串的长度进行减法运算,返回的就是这个减法的结果。如果连个字符串一摸一样 返回的就是0
    public int compareToIgnoreCase(String str) :跟上面一样 只是忽略大小写的比较

  • 案例演示:

    public class StringDemo {
        public static void main(String[] args) {
            //字符串中替换的方法
            String s = "奥巴马是美国总统".replace('马', 'M');
            System.out.println(s);
            String s1 = "奥巴马是美国总统".replace("奥巴马", "***");
            System.out.println(s1);
            String s2 = "奥巴马是美国总统特朗普也是美国总总统".replace("奥巴马", "****").replace("特朗普", "***");
            System.out.println(s2);
            
           //字符串去除两端空格的方法
            String trim = "    abc     ".trim();
            System.out.println(trim);
    
            //对比字符串
            //通过字典顺序去比较 返回的值是 ASCII 码的差值  调用者减去传入者
            int i = "abc".compareTo("Abc");
            System.out.println(i);
            //通过长度去比
            int i1 = "abc".compareTo("a");
            System.out.println(i1);
    
            //忽略大小写的比较
            int abc = "abc".compareToIgnoreCase("ABC");
            System.out.println(abc);
        }
    }
    

String类的其他应用:

  • A.把数组转成字符串

    public class Array2 {
        public static void main(String[] args) {
            int[] arr = {98,23,16,35,72};
            String str = "[";
    
            for (int i = 0; i < arr.length; i++) {
                if(i == arr.length - 1){
                    str += arr[i]+"]";
                }else{
                    str += arr[i]+",";
                }
            }
            System.out.println(str);   //[98,23,16,35,72]
        }
    }
    
  • B:统计大串中小串出现的次数

    public class MyTest5 {
        public static void main(String[] args) {          
        //统计"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun”
        //中java出现了几次
         	String  maxStr=
           "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
            
            String minStr="java";
    
            //把一段代码抽取到一个方法中 ctrl+alt+M
            findStr(maxStr, minStr);
    
            //方式2============================
            int count=0;
            String newStr = maxStr.replace("java", "0");
            System.out.println(newStr);
            for (int i = 0; i < newStr.length(); i++) {
                char ch = newStr.charAt(i);
                if(ch=='0'){
                    count++;
                }
            }
            System.out.println("Java出现的次数" + count + "次");
        }
    
        private static void findStr(String maxStr, String minStr) {
            int count=0;
            //查找java出现的索引
            int index= maxStr.indexOf(minStr);
            while (index!=-1){
                count++;
                maxStr= maxStr.substring(index+4);
                //再次改变索引
                index = maxStr.indexOf(minStr);
            }
            System.out.println("Java出现的次数"+count+"次");
        }
    }
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值