String 类(toCharArray/charAt/equalsIgnoreCase/ startWith/indexOf/split/trim/toLowerCase/substring)

字符与字符串的相互转换:
字符数组转化为字符串
用构造函数:

  • public String(char[ ] value) :将字符数组中所有内容变为字符串
  • public String(char[ ] value,int offset,int count);:将字符数组中部分内容变为字符串

将字符串转为字符数组

  • public char[ ] toCharArray( );

取得字符串中单个字符

  • public char charAt(int index); //取得指定字符
public class StringArray
{
    public static void main(String[] args)
    {
        //将字符数组转为字符串
        char[] ch1=new char[]{'a','b','c','d','e','f','g'};
        String str1=new String(ch1);
        String str2=new String(ch1,1,3);  //从下标1开始数3个字符变为字符串
        System.out.println(str1); //abcdefg
        System.out.println(str2); //bcd

        //取得字符串中一个字符
        char ch=str1.charAt(3); //取得下标为3的字符
        System.out.println(ch);  //d

        //将字符串转为字符数组
        char[] ch2=str1.toCharArray();
        for(char num: ch2)
        {
            System.out.print(num+"、");  //a、b、c、d、e、f、g、
        }
    }
}

面试题:判断一个字符串是否全由数字组成
先拆成字符数组,然后对字符数组里每个字符进行判断。

public class StringArray
{
    public boolean isChar(String str)
    {
        char[] ch=str.toCharArray();  //转为字符数组
        for(int i=0;i<ch.length;i++)
        {
            if(ch[i]<'0'||ch[i]>'9')
            {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args)
    {
       String str=new String("1234abc");
       StringArray strArray=new StringArray();
       if(strArray.isChar(str))
       {
           System.out.println("str是由数字组成");
       }
       else
       {
           System.out.println("str不是由数字组成");
       }
    }
}

字节(byte)与字符串的转换
字节常用于数据传输以及编码转换的处理之中。字节只适合处理二进制数据。
字节数组转为字符串

  • public String(byte[ ] value) :将字节数组中所有内容变为字符串
  • public String(byte[ ] value,int offset,int count);将字节数组中所有内容变为字符串

字符串转为字节数组

  • public byte[ ] getBytes( );
  • public byte[ ] getBytes(String charSetName); : 将字符串按照指定编码转为字节数组
public class CharArray
{
    public static void main(String[] args)
    {
        //将字节数组转化为字符串 
        byte[] by1=new byte[]{1,2,3,4,5,6};  //字节数组,每个元素都是一个字节
        String str1=new String(by1); //将字节数组全部内容转化为字符串 
        String str2=new String(by1,1,4);
        System.out.println(str1);
        System.out.println("******");
        System.out.println(str2);
        
        //将字符串转为字节数组
        byte[] by2=str1.getBytes();
        for(int num : by2)
        {
            System.out.print(num+"、");
        }

        ///将字符串按照指定格式转为字节数组
        String str3=new String("哈喽");
        byte[] by3=str3.getBytes();
        for(int num :by3)
        {
            System.out.print(num+"、");
        }

        // byte[] by4=str3.getBytes("UTF-8")  //按UTF-8编码,UTF-8适用于所有语言
        // for(int num :by3)
        // {
        //     System.out.print(num+"、");
        // }
    }
}

将字节转为字符串输出后:
在这里插入图片描述

字符串比较

  • 区分大小写比较:public boolean equals(String anotjerString);

  • 不区分大小写比较:public boolean equalsIgnoreCase(String anotherString);

  • 比较两个字符串大小:public int compareTo(String anotherString):
    返回大于0:表示大于比较对象,表示两者之间的差值
    返回等于0:两者相等
    返回小于0:表示小于比较对象
    如果比较到两个字符串有不相等字符,就返回,不会再判断后面字符大小。

public class Compare
{
    public static void main(String[] args)
    {
        String str1="hEllo";
        String str2="hellO";
        System.out.println(str1.equals(str2));  //false  区分大小写
        System.out.println((str1.equalsIgnoreCase(str2)));  // true 不区分大小写
        System.out.println(str1.compareTo(str2)); //-32 因为str2的E小于str2的e,小了32,
        //如果比较到两个字符串有不相等字符的,就返回,不会再判断后面字符大小
    }
}

字符串查找

  • public boolean contains(String str): 判断str在本字符串中是否存在
  • public boolean startWith(String str); 判断是否以指定字符串开头
  • public boolean startWith(String str,int index); 从指定位置开始判断是否以指定字符串开头
  • public boolean endWith(String str); 判断是否以指定字符串结尾
  • public int indexOf(String str); 从头开始查找指定字符串,返回字符串第一次出现的位置(下标),没有返回-1
  • public int indexOf(String str,int index) ; 从指定位置查找子串第一次出现位置
  • public int lastIndexOf(String str); 从后向前查找子串位置
  • public int lastIndexOf(String str,int index); 从指定位置从后向前查找子串位置
/////字符串查找
/////字符串查找
public class Compare
{
    public static void main(String[] args)
    {
       String str1="hello world abcd world";
       System.out.println(str1.contains("abc")); //true
       System.out.println(str1.startsWith("world")); //false 不是以world开头
       System.out.println(str1.startsWith("world",6)); //true 从指定位置下标为6判断是否以world开头

       System.out.println(str1.indexOf("world")); //返回world第一次出现的位置 6
       System.out.println(str1.indexOf("world",8));  // 17 从下标为8开始判断world第一次出现的位置

       System.out.println(str1.lastIndexOf("world"));  // 17  //从后向前返回子串地再一次出现位置
       //从指定位置从后向前返回子串第一次出现位置
       System.out.println(str1.lastIndexOf("world",str1.length()-6)); // 6 向前判断str1.length()-6是空格 不符合标准就继续向前判断
       System.out.println(str1.lastIndexOf("world",str1.length()-5)); // 17  str1.lenght()-5是最后一个w位置,判断是world       
       System.out.println(str1.endsWith("cd")); //false 判断是否以cd结尾    
    }
}

字符串替换

  • public String replaceAll(String regex,String replacement); //替换所有指定内容 将regex全部替换为replacement
  • public String replaceFirst(String regex,String replacement); //替换首个内容 将第一个regex全部替换为replacement
public class Compare
{
    public static void main(String[] args)
    {
        String str="hello world hello";
        System.out.println(str.replaceAll("hello","hai"));  //hai world hai  将所有hello替换为hai
        System.out.println(str.replaceFirst("hello","hai")); //hai world hello 将第一个hello替换为hai 
    }
}

字符串拆分

  • public String[ ] split (String regex); :将字符串按照指定格式全部拆分
  • public String[ ] split (String regex,int limit); //将字符串部分拆分,数组长度为limit
    如果超过数组长度,其余不拆分。
public class Compare
{
    public static void main(String[] args)
    {
        //全部拆分
       String str1="hello world,happy day";
       String[] result1=str1.split(" "); // 按空格拆分放到字符串数组中
       for(String num :result1)
       {
           System.out.print(num+"、"); //hello、world,happy、day、拆分成了3个元素
       }

        //部分拆分
       String[] result2 =str1.split(" ",2);
       for(String num :result2)
       {
           System.out.print(num+"、"); //hello、world,happy day、拆分成了2个元素
       }

        //拆分格式需要转义
        String ip="192.168.2.2";  //IP地址
        String[] result3=ip.split("\\.");  //如果发现拆分结果不是期望的,那就是拆分格式有误,可能需要转义
        for(String num : result3)
        {
            //System.out.print(num+"、"); // 192、168、2、2、
        }

        //多次拆分
        String info="jing 10 |ting 15";
        String[] result4=info.split("\\|");
        for(int i=0;i<result4.length;i++)
        {
            String[] result5=result4[i].split(" ");
            System.out.println(result5[0]+"是"+result5[1]+"岁"); //jing是10岁  ting是15岁
        }
    }
}

字符串截取

  • public String substring(int beginIndex); 从指定位置截取到字符串结尾 [ 左闭
  • public String substring(int beginIndex,int endIndex); 截取部分内容 左闭右开 [ )
public class Compare
{
    public static void main(String[] args)
    {
        String str="hello world hai day";
        System.out.println(str.substring(6));//world hai day
        System.out.println(str.substring(0,5)); //hello  左闭右开 
    }
}

String类的其他方法

  • 去掉左右空格,保留其他空格:public String trim( );
  • 转大小写:
    public String toUpperCase( ); :全部转大写
    public String toLowerCase( ); 全部转小写
  • 字符串长度:public int lenght( );(数组长度是length,是属性)
  • 判断字符串是否为空(只能判断是否为空字符串即长度是否为0而不是判null)
    public String isEmpty( );
public class Compare
{
    public static void main(String[] args)
    {
        //去左右空格,大小写转换
        String str="  Hello 中国  ";
        System.out.println(str.trim()); //"Hello 中国"   只会去掉左右空格
        System.out.println(str.toUpperCase());  //  "  HELLO 中国  "  字母全部转大写,但是对汉字无影响
        System.out.println(str.toLowerCase());  //  "  heLLO 中国  "  字母全部转小写,但是对字母无影响

        //判空
        String str2="";
        System.out.println(str2.isEmpty()); 
        String str1=null;   
        //System.out.println(str1.empty());   如果直接这样判断会报错,但是str1确实是空的
        //所以对String类字符串判空推荐如下:
        if(str1==null||str1.isEmpty())
        {
            System.out.println("str1是空串");
        } 
    }
}

String类里没有字符串首字母大写的方法,所以需要我们自己写字符串首字母大写的方法:

public class Compare
{
    public static String firstUpper(String str)
    {
        if(str==null|| str.isEmpty())  //需要判断是否为空
            return null;
        return str.substring(0,1).toUpperCase()+str.substring(1);
    }
    public static void main(String[] args)
    {
        System.out.println(firstUpper("")); //null
        System.out.println(firstUpper(null));//null
        System.out.println(firstUpper("hello world")); //Hello world
        System.out.println(firstUpper("a")); //A
    }
}

猜你喜欢

转载自blog.csdn.net/sophia__yu/article/details/83503017
今日推荐