字符串常见方法总结案例(二)

版权声明:该博客由石头猿在学习过程中自行总结的原创,博客中代码仅供参考,禁止使用非法途径! https://blog.csdn.net/qq_35981996/article/details/84593556
public class StringDemo {

	public static void main(String[] args) {
       String s="xyz";
      //创建2个对象,创建了一个字符串abc对象,另一个对象是abc的副本
       String s1=new String("abc");
       System.out.println(s+" "+s1);
       
       char[]chars={'H','e','e','l','o'};
       s=new String(chars);
       System.out.println(s);
      //字符串的长度
       s="I love java";
       System.out.println("字符串的长度"+s.length()+"数组的长度"+chars.length);
       //循环字符串,获取每个字符
       for(int i=0;i<s.length();i++){
    	   System.out.println(s.charAt(i));//输出字符串中第i个字符
       }
       
       //equals用于比较字符串的内容
       String sa="asdf";
       String sb="asdf";
       //==运算符用于比较两个引用是否指向同一对象,比较内存地址是否一样
       System.out.println(sa==sb);
       //equals比较内容是否相等
       System.out.println(sa.equals(sb));
       
       String sc=new String(sb);
       System.out.println(sb==sc);
       System.out.println(sc.equals(sb));
       
       sa="xyz";
       sb="Xyz";
       //内容需要完全一致
       System.out.println(sa.equals(sb));
       //内容不区分大小写
       System.out.println(sa.equalsIgnoreCase(sb));
       
       //startwith()
       s="asdsf";
       System.out.println(s.startsWith("a"));
       System.out.println(s.startsWith("as",0));
       System.out.println(s.startsWith("sf",3));
       System.out.println(s.endsWith("sf"));
       
       //s.index()返回字符串在此字符串第一次出现的索引
	   System.out.println(s.indexOf("s"));
	   System.out.println(s.indexOf("sf"));
	   System.out.println(s.lastIndexOf("s"));//最后一次s出现的地址
	   System.out.println(s.indexOf("x"));
	  
	   
	   //substring()
	   s="hi, Newer, I am here";
	   //从开始索引3到结束
	   System.out.println(s.substring(3));
	   //从开始索引4到8
	   System.out.println(s.substring(4,8));
	   //将e替换成i
	   System.out.println(s.replace("e","i"));
	   
	  
	   s=" haha lala ";
	   System.out.println(s.length());
	   //trim() 去掉首尾空格
	   System.out.println(s.trim());
	   System.out.println(s.trim().length());
	   
	   //toUpperCase()转大写  toLowerCase()转小写
	   System.out.println("转换大写:"+"xYzAbc".toUpperCase());
	   System.out.println("转换小写:"+"xYzAbc".toLowerCase());
	   
	   
	   //formot()格式化字符串
	   String format="Hi %s,welcome to %s";
	   s=String.format(format,"kobe","大长沙");
	   System.out.println(s);
	   
	   
	   //split()拆分字符串
	   s="香蕉,苹果,橘子,葡萄,榴莲";
	   String[]array=s.split(",");
	   //增强形for循环( :后是数组或者集合    :前是数组或集合中的某一元素)
	   for(String ar:array){
	   System.out.println(ar);
	   }
	   
	   //连接字符串
	   System.out.println("to".concat("get").concat("her"));
	   System.out.println("to"+"get"+"her");
	   }

}

猜你喜欢

转载自blog.csdn.net/qq_35981996/article/details/84593556
今日推荐