Java中关于String类的基本操作(字符与字符串的相互转换、字节与字符串的相互转换、字符串比较、字符串查找、字符串替换、字符串拆分、字符串截取、去掉左右空格、转大小写、判断是否为空)

1 字符与字符串的相互转换

  字符串就是一个字符数组,所以在String类里面支持有字符数组转为字符串以及字符串转为字符的操作方法。

//取得字符串长度:public int length();
//数组的长度:数组名.length;

1.1 将字符数组转为字符串

  用String类的构造方法!

/**
1.  public String(char [] value);将字符数组value中的所有内容变为字符串
2.  public String(char [] value,int offset,int count);将字符数组value中的部分内容变为字符串
offset为开始索引、count为个数

均为成员方法,通过对象调用!!!
*/

public class Test{
   
   
    public static void main(String[] args)
    {
   
   
        //静态初始化一个字符串数组
        char [] arr = new char[]{
   
   'h','e','l','l','o','&','1','3','1','4'};

        //将字符数组中的所有内容变为字符串
        String str1=new String(arr);
        System.out.println(str1);

        //从下表为5的索引开始,将之后的5个字符变为字符串
        String str2=new String(arr,5,5);
        System.out.println(str2);

        //如果,字符的个数超出了数组的范围,运行时会有数组越界异常(StringIndexOutOfBoundsException)
        String str3=new String(arr,5,10);
        System.out.println(str3);

    }
}

在这里插入图片描述

1.2 将字符串转为字符数组

/**
将字符串该为字符数组
1. public char[] tocharArray();
*/
public class Test{
   
   
    public static void main(String[] args)
    {
   
   
      String str="hello";
      char [] result=str.toCharArray();
      //for-each循环
      for(char i:result)
      {
   
   
          System.out.print(i+" ");
      }
    }
}

在这里插入图片描述

1.3 将字符串转为单个字符

/**
1. public char charAt(int index);取得指定索引位置上的字符
index:索引
*/

public class Test{
   
   
    public static void main(String[] args)
    {
   
   
        //取得索引为0的位置的字符
        System.out.println("hello".charAt(0));
        //如果索引越界,会报数组越界异常StringIndexOutOfBoundsException
        System.out.println("hello".charAt(6));
    }
}

在这里插入图片描述

1.4 判断一个字符串是否由数字组成?

/**
判断一个字符串是否由数组组成
取得字符串长度:public int length();
取得数组的长度:数组名.length
*/


public class Test{
   
   
    public static boolean isNumber1(String str)
    {
   
   
        for(int i=0;i<str.length();i++)
        {
   
   
            //将字符串根据索引转成单个字符
            char result=str.charAt(i);
            if(result<'0'||result>'9')
            {
   
   
                return false;
            }
        }
        return true;
    }
    public static boolean isNumber2(String str)
    {
   
   
        //将字符串转为字符数组
        char [] data=str.toCharArray();
        for(int i=0;i<data.length;i++)
        {
   
   
            if(data[i]<'0'||data[i]>'9')
            {
   
   
                return false;
            }
        }
        return true;

    }
    public static void main(String[] args)
    {
   
   
      String str="14263";
      System
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值