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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值