String类

String类

Scanner的概述和方法介绍

一.Scanner的概述

  • 一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器

二.Scanner的构造方法原理

  • Scanner(InputStrram source)
  • System类下有一个静态的字段

public static final InputStream in; 标准的输入流,对应着键盘输入

三.一般方法

  • hasNextXxx() 判断是否还有下一个输入项,其中Xxx可以是Int,Double等。如果需要判断是否包含下一个字符串,则可以省略Xxx
  • nextXxx() 获取下一个输入项。Xxx的含义和上个方法中的Xxx相同,默认情况下,Scanner使用空格,回车等作为分隔符

案例分析

public class Demo1_Scanner {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);       //键盘录入
		//int i = sc.nextInt();                    //键盘录入整数存储在i中
		//System.out.println(i);
		if (sc.hasNextInt()) {
			int i = sc.nextInt();
			System.out.println(i);
		} else {
			System.out.println("输入类型错误");
		}
	}
}

四.Scanner获取数据中出现的问题

1.两个常用的方法

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

2.案例演示

  • 先演示获取多个int值,多个String值得情况
  • 然后演示现获取int值,再获取String值出现问题

解决方案

  • 先获取一个数值后,在创建一个新的键盘录入对象获取字符串
  • 把所有的数据都酰胺字符串获取,然后要什么,就对应的转换成什么

案例演示

import java.util.Scanner;

public class Demo2_Scanner {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		/*
		 * System.out.println("请输入第一个整数:");       //只录入整数
		 * int i = sc.nextInt();
		 * System.out.println("请输入第一个整数:");
		 * int j = sc.nextInt();
		 * System.out.println("i = " + i + "," + "j = " + j);
		 */
		 
		/*
		 * System.out.println("请输入第一个字符串:");     //只录入字符串
		 * String line1 = sc.nextLine();
		 * System.out.println("请输入第二个字符串:"); 
		 * String line2 = sc.nextLine();
		 * System.out.println(); System.out.println("line1 = " + line1 + "   " + "line2 = " + line2);
		 */
		
		/*
		 * System.out.println("请输入第一个整数:");         //既录入整数,又录入字符串
		 * int i = sc.nextInt();
		 * System.out.println("请输入第二个字符串:"); 
		 * String line2 = sc.nextLine();
		 * System.out.println("i = " + i + " " + "line2 = " + line2);
		 */
		/*
		    解决方案
		    1.创建两次对象,但是浪费空间
		    2.键盘录入的都是字符串,都用nextLine方法,后面我们会学习将整数字符转换成整数的方法
		 */
		System.out.println("请输入第一个整数:"); 
		int i = sc.nextInt();
		Scanner sc2 = new Scanner(System.in);
		System.out.println("请输入第二个字符串:"); 
		String line2 = sc2.nextLine();
		System.out.println("i = " + i + " " + "line2 = " + line2);
	}
}

String类

一.String类的概述

  • java.lang.String
  • 字符串字面值"abc"也可以看成是一个字符串对象
  • 字符串是常量,一旦被赋值,就不能被改变

案例演示

public class Demo1_String {
	public static void main(String[] args) {
		//person p = new person();
		String str = "abc";                     //"abc"可以看成一个字符串对象
		str = "def";                            //当把"def"赋值给str,原来的"abc"就变成了垃圾
		System.out.println(str);                //String类重写了toString方法,返回的是该对象本身
		System.out.println(str.toString());
	}
}

二.常见的String类构造方法

  • 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):把字符串常量值转成字符串

案例演示

public class Demo2_StringConstract {
	public static void main(String[] args) {
		String s1 = new String();
		System.out.println(s1);//
		
		byte [] arr1 = {97,98,99};                 //解码:将计算机读得懂得转换成我们读的懂得
		String s2 = new String(arr1);
		System.out.println(s2);//abc
		
		byte[] arr2 = {97,98,99,100,101,102};      //将arr2字节数组从2索引开始转换3个
		String s3 = new String(arr2,2,3);
		System.out.println(s3);//cde
		
		char[] arr3 = {'a','b','c','d','e'};       //将字符数组转换成字符串
		String s4 = new String(arr3);
		System.out.println(s4);//abcde
		
		String s5 = new String(arr3,1,3);          //将arr3字符数组,从1索引开始转换3个
		System.out.println(s5);//bcd
		
		String s6 = new String("heima");
		System.out.println(s6);//heima
	}
}

三.String类的判断功能

1.方法

  • boolean equals(Object obj):比较字符串的内容是否相等,区分大小写
  • boolean equalsIgnoreCase(String str):比较字符串的内容是否相等,忽略大小写
  • boolean contains(String str):判断大字符串中是否包含小字符串
  • boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
  • boolean endWith(String str):判断字符串是否以某个指定的字符串结尾
  • boolean isEmpty():判断字符串是否为空

案例演示

public class Demo4_StringMethod {
	public static void main(String[] args) {
		demo1();
		demo2();
		demo3();
	}

	private static void demo3() {
		String s1 = "heima";
		String s2 = "";
		//String s3 = null;
		
		System.out.println(s1.isEmpty());//false
		System.out.println(s2.isEmpty());//true
		//System.out.println(s3.isEmpty());//空指针异常
	}

	private static void demo2() {
		String s1 = "我爱heima,hh";
		String s2 = "heima";
		String s3 = "baima";
		String s4 = "我爱";
		String s5 = "hh";
		
		System.out.println(s1.contains(s2));//true
		System.out.println(s1.contains(s3));//false
		
		System.out.println("——————————");
		System.out.println(s1.startsWith(s4));//true
		System.out.println(s1.startsWith(s5));//false
		
		System.out.println("——————————");
		System.out.println(s1.endsWith(s4));//false
		System.out.println(s1.endsWith(s5));//true
	}

	private static void demo1() {
		String s1 = "heima";
		String s2 = "heima";
		String s3 = "HeiMa";
		
		System.out.println(s1.equals(s2));//true
		System.out.println(s2.equals(s3));//false
		
		System.out.println("————————");
		
		System.out.println(s1.equalsIgnoreCase(s2));
		System.out.println(s1.equalsIgnoreCase(s3));
	}
}

补充

""与null的区别
“”是字符串常量,同时也是一个String类的对象,既然是对象当然可以调用String类的中的方法
null是空常量,不能调用任何的方法,否则会出现空指针异常,null常量可以给任意的引用数据类型赋值

四.模拟用户登录

1.需求:模拟登录,给三次机会,并提示还有几次

2.分析:

  • 模拟登陆需要键盘录入,Scanner
  • 给三次机会,需要循环,for
  • 并提示有几次,需要判断,if

案例演示

public class Test1 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		for (int i = 0; i < 3; i++) {
			System.out.println("请输入用户名:");
			String useName = sc.nextLine();
			System.out.println("请输入密码:");
			String password = sc.nextLine();
			
			if ("ljhdsg".equals(useName) && "ljhdsg".equals(password)) {
				System.out.println("欢迎" + useName);
				break;
			} else {
				if (i == 2) {
					 System.out.println("您没有机会了,请明天再来!!!");
				} else {
					System.out.println("用户名或密码错误,你还有" + (3-i-1) + "次机会");
				}
			}
		}
	}
}

五.String类的获取功能

  • 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):返回指定字符串在此字符串中从指定位置后第一次出现的索引
  • lastIndexOf()
  • String substring(int start):从指定位置开始截取字符串,默认到末尾
  • String substring(int start,int end):从指定位置开始到指定位置结束截取字符串(包含头不包含尾)

案例演示

public class Demo4_Stringmethod2 {
	public static void main(String[] args) {
		//demo1();
		//demo2();
		//demo3();
		//demo4();
		//demo5();	
	}

	private static void demo5() {
		String s1 = "heimawudi";
		s1.substring(4);                      //substring会产生一个新字符串,需要将新的字符串记录
		System.out.println(s1);
	}

	private static void demo4() {
		//String substring(int start)
		String s1 = "heimawudi";
	    String index1 = s1.substring(5);
		System.out.println(index1);
		//String substring(int start,int end)
		String index2 = s1.substring(0,5);          //左闭右开
		System.out.println(index2);
	}

	private static void demo3() {
	    //int indexOf(int ch,int fromIndex)
     	String s1 = "woaiheima";
		int index1 = s1.indexOf('a', 3);         //从指定位置向后找第一次出现的索引
		System.out.println(index1);
		//lastIndexOf(int ch)
		int index2 = s1.lastIndexOf('a');
		System.out.println(index2);             //从后向前找第一个出现的索引
		//lastIndexOf(int ch,int fromIndex)
		int index3 = s1.lastIndexOf('a',7);    //从指定位置向前找
		System.out.println(index3);
	}

	private static void demo2() {
		//int indexOf(int ch)
		String s1 = "heima";
		int index = s1.indexOf('a');        //参数接收的是int类型的,传递char类型的会自动提升
		System.out.println(index);
		
		int index2 = s1.indexOf('z');      //如果不存在就返回-1
		System.out.println(index2);
		//int indexOf(String str)
		int index3 = s1.indexOf("ma");    //获取字符串中第一个字符出现的位置(字符连续)
		System.out.println(index3);
		
		int index4 = s1.indexOf("ia");    //获取字符串中第一个字符出现的位置(字符不连续)
		System.out.println(index4);
	}

	private static void demo1() {
		//int length()
		String s1 = "heima";
		System.out.println(s1.length());
		String s2 = "你是大帅哥吗?";
		System.out.println(s2.length());
		//char charAt(int index)
		char c = s2.charAt(4);            //下标
		System.out.println(c);                   
		//char c2 = s2.charAt(10);       //索引越界异常
		//System.out.println(c2);
	}
}

六.String类的转换功能

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

案例演示

import com.heima.bean.Person;

public class Demo4_StringMethod3 {
	public static void main(String[] args) {
		//demo1();
		//demo2();
		//demo3(); 
		//demo4();
	}

	private static void demo4() {
		String s1 = "heiMa";
		String s2 = "chengxuYUAN";
		String index1 = s1.toLowerCase();
		String index2 = s2.toUpperCase();
		
		System.out.println(index1);
		System.out.println(index2);
		
		System.out.println(index1 + index2);        //用+拼接字符串更强大,可以用字符串与任意类型拼接
		System.out.println(index1.concat(index2));  //concat方法调用的和传入的都必须是字符串		
	}

	private static void demo3() {
		char[] arr = {'a','b','c'};
		String s = String.valueOf(arr);            //底层是由String类的构造方法完成的(不用再创建对象)
		System.out.println(s);
		
		String s2 = String.valueOf(100);
		System.out.println(s2 + 100);
		
		Person p1 = new Person("张三",23);
		String s3 = String.valueOf(p1);            //调用的是对象的toString方法
		System.out.println(s3);
	}

	private static void demo2() {
		String s = "heima";
		char[] arr = s.toCharArray();             //将字符串转换成字符数组
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
	}

	private static void demo1() {
		String s1 = "abc";
		byte[] arr = s1.getBytes();                //把字符串转换为字符数组    
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		
		String s2 = "你好你好";
		byte[] arr2 = s2.getBytes();               //通过gdk码表将字符串转换成字符数组
		for (int i = 0; i < arr2.length; i++) {    //编码:把我们看的懂得转换成计算机看得懂的
			System.out.print(arr2[i] + " ");       //gdk码表一个中文代表两个字节
		}                                          //gdk码表的特点:中文的第一个字节肯定是负数
		System.out.println();
		
		String s3 = "非";
		byte[] arr3 = s3.getBytes();
		for (int i = 0; i < arr3.length; i++) {
			System.out.print(arr3[i] + " ");
		}
		System.out.println();
	}
}

七.String类的其他功能

1.String的替换功能

  • String replace(char old,char new)
  • String replace(String old,String new)

2.String的去除字符串两端空格

  • String trim()

3.String的按字典顺序比较两个字符串

  • int compareTo(String str):管大小写
  • int compareToIngnoreCase(String str):不管大小写

案例演示

public class Demo4_StringMethod4 {
	public static void main(String[] args) {
		//demo1();
		//demo2();
		//demo3();		
	}

	private static void demo3() {
		String s1 = "a";
		String s2 = "aaaa";
		
		int num = s1.compareTo(s2);
		System.out.println(num);//-3
		
		String s3 = "黑";
		String s4 = "马";                           
		int num2 = s3.compareTo(s4);           
		System.out.println('黑' + 0);//40657          //查找的是unicode码表值
		System.out.println('马' + 0);//39532
		System.out.println(num2);//1125(40657-39532)
		
		String s5 = "heima";
		String s6 = "HEIMA";
		int num3 = s5.compareTo(s6);
		System.out.println(num3);//32
		
		int num4 = s5.compareToIgnoreCase(s6);
		System.out.println(num4);//0
	}

	private static void demo2() {
		String s = "    hei   ma   ";
		String index1 = s.trim();
		System.out.println(index1);//hei   ma
	}

	private static void demo1() {
		String s = "heima";
		String index1 = s.replace('i', 'o');        //s中存在'i'
		System.out.println(index1);//heoma
		
		String index2 = s.replace('k', 'o');        //s中不存在'k',保留原字符不改变
		System.out.println(index2);//heima
		
		String index3 = s.replace("ei", "ao");
		System.out.println(index3);//haoma
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值