String的用法

1.使用indexOf实现检索给定字符串在当前字符串中的位置(从0开始)
  String str = "thinking in java";
  //检索第一次出现指定字符串的位置
  System.out.println(str.indexOf("in"));//2


  //从指定位置开始检索第一次出现指定字符串的位置
  System.out.println(str.indexOf("in",3));//5


  //检索最后一次出现指定字符串的位置
  System.out.println(str.lastIndexOf("in"));//9
  System.out.println(str.indexOf('b'))//-1(不包含给定的字符)


2.使用substring获取位置的字符串(含头不含尾)
  String str = "HelloWorld";
  String subStr = str.substring(0,5);  
  System.out.println(subStr)//Hello


3.使用trim去除字符串两边的空白
  String str ="  Hello   World        ";
  String trim = str.trim();
  System.out.println(trim);// Hello   World


4.使用charAt给定下标位置来获取该字符串中这个位置的字符
  String str = "HelloWorld";
  char chr = str.charAt(5);
  System.out.println(chr);//W


5.使用startsWithendsWith来判断是否是以给定的字符串开始和结尾的
  String str = "java.jpg";
  if(str.endsWith(".jpg")){
  System.out.println("是一张图片");
  }else{
  System.out.println("不是一张图片");
  }


6.使用toUpperCase()toLowerCase()来将当前字符串中的英文部分的字符
  全部变为大写和小写后再将新的字符串返回
  String str = "HelloWorld";
  String lower = str.toLowerCase();
  String upper = str.toUpperCase();
  System.out.println(lower);//helloworld
  System.out.println(upper);//HELLOWORLD


7.使用valueOf将java中其他类型转换为字符串(字符串提供了一组重载的静态方法)
  double a=23.23;
  String a1=String.valueOf(a);
  System.out.println(a1+4);//23.234


  char[] charArr = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }; 
  String str = String.valueOf(charArr);
  System.out.println(str);//abcdefg


8.使用length()来获取字符串的长度
  String str="thinking in java";
  System.out.println("length:"+str.length());//16


9.使用equals()来判断字符串是否相等(判断内容)
  String str1="helloworld";//字面量形式创建会存储字符串常量池——>堆内存中
  str1=str1+"!";
  String str2="helloworld";
  System.out.println(str1==str2);//false(指向新对象)

  String str3="helloworld";
  System.out.println(str2==str3);//true(判断指向对象是不是同一个对象)

  String str4=new String("helloworld");
  System.out.println(str2.equals(str4));//true
  System.out.println(str2==str4);//false(new一定创建新对象)

  String str5="hello"+"world";//两个字面量相加,编译器编译.class就编译好
  System.out.println(str2==str5);//true

  String s="hello";//字符串常量池
  String str6=s+"world";//修改字符串内容一定创建新对象
  System.out.println(str1.equals(str6));//true
  System.out.println(str2==str6);//false


10.字符型数组转为字符串类型,再转为大写字母
  char[] arrChar= new char[5]{a,b,c,d,c};
  String str1=new String(arrChar).toUpperCase();


11.字符串类型转为字符型数组
  String str="HelloWorld";
  char[] arrChar=str.toCharArray();
  System.out.println(arrChar);//HelloWorld

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linsa_pursuer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值