String 类Scanner类的常见用法已经特殊字符如何处理

一 Scanner 类 hasNext(),和hasNextLine() 用法区别

public static void main(String[] args){
     Scanner  sn = new Scanner(System.in);

     if(sn.hasNextLine()){
       String msg = sn.nextLine();
       System.out.println("你输入的字符串是:"+msg);

       System.out.println(msg.length()-msg.lastIndexOf(" "));

  }


}

hellow world
你输入的字符串是:hellow world
6

public static void main(String[] args){
     Scanner  sn = new Scanner(System.in);

     if(sn.hasNext()){
       String msg = sn.next();
       System.out.println("你输入的字符串是:"+msg);

       System.out.println(msg.length()-msg.lastIndexOf(" "));

  }


}

hellow world
你输入的字符串是:hellow
7

由上述的结果,可以得到: 
next()对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或者结束符,所以next()方法读取的是不能带空格的字符串。 
nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
二: String 类 的常见用法

public static void main(String[] args){
   Scanner  sn = new Scanner(System.in);
   if(sn.hasNextLine()){
      String msg = sn.nextLine();
    //   String newmsg =  msg.replace(" ","");   // 用空格截取(1)
       String newmsg =    msg.replaceAll("\\s",""); // 用空格截取(2)
      System.out.println("msg:"+msg);
      System.out.println("newmsg:"+newmsg);

   }

   String s ="sdf//a//aa";

   System.out.println(s);
   System.out.println(s.replaceAll("////", "////////////////////"));
   System.out.println(s.replaceAll("////", "/"));
   System.out.println(s.replace("//", "////"));


}

String 类 API(很实用)

判断字符串中的大小写和数字

ASCII 码表 0—48 A—65 a—97 
做大于等于加减乘除等操作的时候,char类型首先会转成int类型。

https://blog.csdn.net/u011301372/article/details/80061935

发布了12 篇原创文章 · 获赞 0 · 访问量 2018

猜你喜欢

转载自blog.csdn.net/LOVELYJF/article/details/102838377
今日推荐