字符串复习

package com.hanqi;

public class Bird1 
{
    public static void main(String[] args)
   {
        //1.定义字符串
        //方法一
        
        String str="字符串常量字符串常量";
        
        System.out.println("ser=" +str);
        
        //方法二
        
        String str1=new String("字符串常量");
        
        System.out.println("str1=" +str1);
        
        //方法三
        
        char[] a={'字','符','串','常','量'};
        
        String str2=new String(a);
        
        System.out.println("str2=" +str2);
        
        //2.字符串比较
        
        //==运算,比较的是内存的地址是否相等,而new则是开辟了新的内存空间,所以字符串不能用==判断
        
        System.out.println("str1与str2是否相等:" +str1.equals(str2));
        
        //3.字符串长度
        
        //str.length();()表示方法,不带()表示属性
        
        System.out.println("“字符串常量字符串常量”的长度是:"  +str.length());
        
        //4.查找字符串中子字符串的位置
        
        //4.1从前往后查找字符串中子字符串的位置,返回找到之后的首字的索引值
        
        System.out.println("串的位置在第" +str.indexOf("串")+"位");
        
        System.out.println("“串常”的位置在第" +str.indexOf("串常") +"位");//当判断多个字符时,只返回首个字符的位置
        
        System.out.println("当查找的子字符串首字在其中,其后不在时:"  +str.indexOf("串字"));//返回-1
        
        //4.2从后面找首字的位置
        
        System.out.println("倒数第一个串的位置在第" +str.lastIndexOf("串"));
        
        //4.3查找不到,返回-1,可以用来判断字符串中是否包含某一个字符串
        
        System.out.println("“我”是不是在str中:" +str.indexOf("我"));
        
        //5.获取字符,获取字符串str中第四位的字符
        
        str="字符串常量字符串常量";
        
        System.out.println("字符串str中第四位的字符是:" +str.charAt(4));
        
        //System.out.println("超字符串长度的结果:"  +str.charAt(str.length()));超字符串长度时报错
        
        //6.判断字符串的开始和结束
        
        //6.1 判断字符串的开始
        
        System.out.println("字符串str是不是以“字符”开始:" +str.startsWith("字符"));//方法1
        
        System.out.println("字符串str是不是以“字符”开始:"  +(str.indexOf("字符")==0) );//方法2
        
        System.out.println("字符串str是不是以“字符”开始:" +(str.charAt(0)=='字'&& str.charAt(1)=='符'));//方法3
        
        //6.2 判断字符串的结束
        
        System.out.println("字符串str是不是以“常量”结束:" +str.endsWith("常量"));//方法1
        
        System.out.println("字符串str是不是以“常量”结束:" +(str.lastIndexOf("常量")==str.length()-2));//方法2
        
          
   }
}
View Code

原文地址:https://www.cnblogs.com/wangchuanqi/p/5240462.html