java字符串

字符串的声明

  1. 双引号赋值

    String x = "a";
    String y = "a";
    System.out.println(x==y);			//true
    System.out.println(x.equals(y));	//true
    

    同一个String字面值无论被创建多少次,始终只有一个内存地址被分配;

    “==”:引用指向同一地址

    “equal”:内存中内容相同

  2. 构造器创建

    String a = new String("abcd");
    String b = new String("abcd");
    		
    System.out.println(a==b);			//false
    System.out.println(a.equals(b));	//true
    

    不同对象会在堆中分配不同的内存空间;

  3. 其他类型转换


字符串的连接

String s1 = new String("hello ");
String s2 = new String("world");
System.out.println(s1 + s2);

int booktime = 4;
System.out.println("我每天看书" + booktime +"小时");
  1. 字符串之间相连:直接连起来

  2. 其他类型相连:自动调用toString()转换成字符串进行连接

获取字符串信息

  1. 字符串长度:.length()

    str.length();
    
  2. 字符查找:.indexOf().lastIndexOf()

    String str = "hello world";
    int index1 = str.indexOf("l");    	//index1=2
    int index2 = str.lastIndexOf("l");	//index2=9
    

    indexOf():返回首次匹配的位置

    lastIndexOf():返回最后一次匹配的位置

  3. 字符获取:.charAt()

    String str = "hello world";
    str.charAt(4); 					//o
    
  4. 字符替换:.replace()

    String str = "hello world";
    str.replace("e","E") 					//hEllo world
    
  5. 子串获取:.substring()

    String str = "hello world";
    str.substring(0,3) 					//hel
    
  6. 空格去除:.trim()

    String str = "  hello world  ";
    str.trim() 					//hello world
    

    去除首尾空格

  7. 开头/结尾判断:.startsWith().endsWith()

    String str = "hello world";
    str.startsWith("he"); 					//true
    str.endsWith("rl")						//false
    
  8. 字符串相等判断:.equals()

    判断内存中的值是否相同,而不是地址是否相同(==)

  9. 字符大小写转换:.toLowerCase().toUpperCase()

    String str = "abc DEF";
    System.out.println(str.toLowerCase());
    
  10. 字符串分割:.split()

    String str = "abc DEF";
    String[] newstr = str.split(" ");
    for (int i = 0; i < newstr.length; i++) {
       System.out.println(newstr[i]);
    }
    

格式化字符串

String.format()用于创建格式化的字符串

  1. 常规类型格式化

    String str = String.format("%d", 400/2);		//结果以十进制显示
    
  2. 日期格式化

    Date date = new Date;
    String s = String.format("%te", date);
    
  3. 时间格式化

    Date date = new Date;
    String hour = String.format("%tH", date);
    String minute = String.format("%tM", date);
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值