zoukankan      html  css  js  c++  java
  • Java-15 String类

    2.2String类

    2.2.1String类简介:
    • 字符串是由多个字符组成的一串数据,它可以认为一个字符数组。
    public class StringDemo {
    	public static void main(String[] args) {
    		// 空串打印
    		String s = new String();
    		System.out.println(s);
    		byte[] bs = {97,98,99};
    		// 把byte数组中数据转成字符串并打印
    		String s2 = new String(bs);
    		System.out.println(s2);//abc
    		String s3 = new String(bs,1,2);
    		System.out.println(s3);// bc
    		
    		char[] chs = {'哈', '你'};
    		String s4 = new String(chs);
    		System.out.println(s4);// 哈你
    		
    		String s6 = new String("拜拜了");
    		System.out.println(s6);// 拜拜了
    	}
    }
    
    2.2.2 String 内存分析

    通过string s = "hello" 方式分配空间存放在常量池中, s4创建发现常量池有"hello"字符串索引s等于s4.
    而通过new创建s2,s3都是在堆中开辟空间。
    
    • 内存分析:通过反编译方式分析。
    public class StringDemo3 {
    	public static void main(String[] args) {
    		String s = "hello";
    		s += "world";
    		System.out.println(s);
    		
    		String s2 = "helloworld";
    		System.out.println(s == s2);// false
    	}
    }
    // 可以看到上面s 没有存储到常量池,否则结果为true。那是怎么看出来的呢,通过XJad将.class文件反编译成.java   可以看到如下s生成是通过new出来的,证明它是堆中创建的
    s = (new StringBuilder(String.valueOf(s))).append("world").toString();
    
    
    // 当我们使用 加号进行字符串拼接时候,如果里面有变量那么它存放在堆内存中,没有变量它存在常量池中。
    
    • 练习
    public class StringDemo4 {
    	public static void main(String[] args) {
    		String s = "hello";
    		String s2 = new String("hello");
    		System.out.println(s == s2);// false
    		System.out.println(s.equals(s2));// true
    		System.out.println(s.hashCode() == s2.hashCode());// true
    	}
    }
    
    • 练习模拟登录:输入三次错误,提示不能登录。
    import java.util.Scanner;
    
    public class lianxi {
    	public static void main(String[] args) {
    		String userName = "ming";
    		String password = "123456";
    		Scanner sc = new Scanner(System.in);
    		for (int i=0;i<=2;i++) {
    			System.out.println("请输入用户名:");
    			String name = sc.next();
    			System.out.println("请输入密码:");
    			String pwd = sc.next();
    			if (userName.equals(name) && password.equals(pwd)) {
    				System.out.println("登录成功");
    				break;
    			} else {
    				if (i == 2) {
    					System.out.println("您今天机会已用完。");
    				} else {
    					System.out.println("用户名密码错误,你还有" + (2-i) + "次机会。");
    				}
    			}
    		}
    	}
    }
    
    2.2.3 String中的方法
    • equals:比较字符串的内容
    public class StringDemo5 {
    	public static void main(String[] args) {
    		String s = "hello";// s是一个string对象
    		System.out.println(s.equals("hello"));// true
    	}
    }
    
    
    • equalsIgnoreCase: 忽略大小写比较字符串的内容
    String s = "hello";// s是一个string对象
    System.out.println(s.equalsIgnoreCase("HellO"));// true
    
    • contains: 包含字符串
    String s = "hello";// s是一个string对象
    System.out.println(s.contains("h"));//true
    
    • startsWith: 以...开头
    String s = "hello";// s是一个string对象
    System.out.println(s.startsWith("h"));//true
    
    • endsWith:以...结尾
    String s = "hello";// s是一个string对象
    System.out.println(s.endsWith("o"));//true
    
    • isEmpty: 空字符串
    String s2 = new String();
    System.out.println(s2.isEmpty());// true
    
    • length: 获取字符串长度
    String s = "hello";// s是一个string对象
    System.out.println(s.length());// 5
    
    • charAt:得到index所对应的字符
    String s = "hello";// s是一个string对象
    for (int i=0;i<s.length();i++) {
    	System.out.println(s.charAt(i));
    }
    // h
    // e
    // l
    // l
    // o
    
    • indexOf:返回str,第一次在字符串中出现索引
    System.out.println(s.indexOf("l"));// 2
    
    • substring(int start):字符串截取,从start对应的索引开始,截到最后
    • substring(int start, int end) :字符串截取,从start对应的索引开始,截到end 包含start,不包含end
    System.out.println(s.substring(2));// llo
    

    练习:统计一个字符串的大写,小写字母,数字出现次数

    
    public class lianxi2 {
    	public static void main(String[] args) {
    		String s = "abcDeFGHIJKlmn293857O8P2qR3St";
    		int count1 = 0;
    		int count2 = 0;
    		int count3 = 0;
    		for (int i=0;i<s.length();i++) {
    			char ch = s.charAt(i);
    			if (ch>='a' && ch<='z') {
    				count1++;
    			}
    			if (ch >= 'A' && ch <= 'Z') {
    				count2++;
    			}
    			if (ch>='0' && ch<='9') {
    				count3++;
    			}
    		}
    		System.out.println("小写字母个数:" + count1);
    		System.out.println("大写字母个数:" + count2);
    		System.out.println("数字个数:" + count3);
    	}
    }
    // 小写字母个数:9
    // 大写字母个数:11
    // 数字个数:9
    
    • getBytes:把一个字符串转成byte
    String s = "hello";// s是一个string对象
    byte[] bs = s.getBytes();
    System.out.println(bs[0]);// 104
    System.out.println(bs[1]);// 101
    
    String s2 = "大";
    byte[] bs2 = s2.getBytes();
    System.out.println(bs2.length);// 3
    
    • toCharArray() :转成char数组
    String s2 = "大家好";
    char[] chs = s2.toCharArray();
    System.out.println(chs.length);// 3
    
    • valueOf(int i):把int转成字符串
    int a = 100;
    String s3 = a + "";
    String s4 = String.valueOf(a);
    
    • toLowerCase: 转成小写
    System.out.println("ADF".toLowerCase());// adf
    
    • toUpperCase:转成大写
    System.out.println("asd".toUpperCase());// ASD
    
    • concat(string str):字符串拼接(只能拼接字符串)
    String s = "hello";// s是一个string对象
    String s2 = "大家好";
    System.out.println(s.concat(s2));// hello大家好
    

    练习:首字母转大写,其余字母转小写

    String s1 = "how Old arE yOu";
    System.out.println(s1.substring(0,1).toUpperCase().concat(s1.substring(1).toLowerCase()));// How old are you
    
    • replace(char old,char new) 或replace(String old,String new):替换
    String str = "你好啊";
    String re = str.replace("你", "我");
    System.out.println(re);// 我好啊
    
    • trim():取出首尾空格
    String s2 = " sd  a    ";
    System.out.println(s2.trim());// sd  a
    
    • compareTo(String str):按照字典顺序比较
    // 可用于按字母进行排序
    System.out.println("abc".compareTo("def"));// -3
    System.out.println("abc".compareTo("abd"));// -1
    
    • compareToIgnoreCase(String str):不区分大小写按照字典顺序比较
    System.out.println("abc".compareToIgnoreCase("ABC"));// 0 
    

    2.3StringBuffer/StringBuilder

    • String类型和StringBuffer区别在于String是不可变对象,因此每次对String类型进行改变时候其实都等同于生成一个新的String对象,然后将指针指向新的String对象。所以经常改变内容的字符串最好不要用String,因为每次生成对象都会对系统性能产生影响。特别当内存中无引用对象多了以后。

    • StringBuffer是线程安全的,StringBuilder是线程不安全的

    2.3.1StringBuffer构造方法
    StringBuffer buffer1 = new StringBuffer();
    System.out.println(buffer1);// 空串
    
    StringBuffer buffer2 = new StringBuffer(32);
    System.out.println(buffer2.length());// 0
    
    StringBuffer buffer3 = new StringBuffer("哈哈");
    System.out.println(buffer3);// 哈哈
    
    2.3.2StringBuffer常用方法
    • append:追加
    StringBuffer s = new StringBuffer("哈哈");
    StringBuffer s2 = s.append("hello").append("world");
    System.out.println(s2);// 哈哈helloworld
    
    • insert:插入
    // 第一个是要插入位置,第二个是要插入内容
    System.out.println(s2.insert(3, "我去"));// 哈哈h我去elloworld
    
    • deleteCharAt:删除执行索引对应的字符
    StringBuffer s = new StringBuffer("哈哈");
    System.out.println(s.deleteCharAt(0));// 哈
    
    • delete(int start, int end):删除从[start, end)
    StringBuffer s = new StringBuffer("你好啊小伙子");
    System.out.println(s.delete(1,3));// 你小伙子
    
    • replace(int start, int end, String str):替换
    StringBuffer s = new StringBuffer("你好啊小伙子");
    System.out.println(s.replace(0, 3, "我去"));// 我去小伙子
    
    • reverse:反转
    StringBuffer s = new StringBuffer("你好啊小伙子");
    System.out.println(s.reverse());// 子伙小啊好你
    
    • substring(int start)或substring(int start,int end):字符串截取(源对象不变,结果在返回值中)
    StringBuffer s = new StringBuffer("你好啊小伙子");
    String s2 = s.substring(1);
    System.out.println(s2);// 好啊小伙子
    
    String s2 = s.substring(1,3);
    System.out.println(s2);// 好啊
    
    • String互相转换StringBuffer
    String转StringBuffer   使用StringBuffer 构造方法  // StringBuffer buffer3 = new StringBuffer("哈哈");
    StringBuffer转String   使用toString // System.out.println(s.toString());
    
  • 相关阅读:
    HDU 5698 瞬间移动
    HDU 5695 Gym Class
    HDU 5694 BD String
    HDU 5692 Snacks
    HDU 5691 Sitting in Line
    胜利大逃亡
    BFS(广度优先搜索)
    计算直线的交点数
    Division
    Jesse's Code
  • 原文地址:https://www.cnblogs.com/xujunkai/p/13795954.html
Copyright © 2011-2022 走看看