Java字符串操作

字符串的构造方法

字符串的特点:

  1. 字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。例如:
  String str = "abc";

等效于

  char data[] = {'a', 'b', 'c'};
  String str = new String(data);
  1. 因为 String 对象是不可变的,所以可以共享。

  2. 字符串底层相当于用一个字节byte数组来存储相关的值

常见3种构造方法

public String ():空白字符

public String (char []array):根据字符数组创建字符串

public (byte []array)


获取功能的方法

public int length():返回此字符串的长度

public String concat(String str):将指定的字符串连接到该字符串的末位
//实际上可以直接拼接 str1+""+str2

public char charAt(int index):返回指定索引处的char值

pubic int indexOf(String str):返回指定字符串第一次出现在该字符串 的索引

public String substring(int beginIndex):返回一个子字符串,该字符串从beginIndex开始截取字符串到字符串结尾。

public String substring(int beginIndex,int endIndex):返回指定索引区间的字符串


转换功能的方法

pubic char toCharArray():将此字符串转化为新的字符数组
public String replace(String a,String b) :将与a匹配的字符串使用b字符串替换
public void reverse() :将字符串反转


分割功能的方法

注意:转义字符前必须加上\
“.$|()[{^?*+\”

pubilc String[]split(String regex):以regex规则拆分为字符数组
String s="abcdef"
String[]array=s.split("bc");
//array[]:{"a","def"}

案例分析

String类字符串的拼接:
利用concat方法从头到尾添加

例子:将String[] arr={“Hello”,“the”,“wolrd”};拼接成[Hello the world]格式

package com.qustion;

public class Stringtest {
    public static void main(String[] args) {
        String[] arr={"Hello","the","wolrd"};
        String res=ArrayToString(arr);
        System.out.println(res);
    }
    public static String ArrayToString(String[] arr){//这里的方法需设置为static
        String s=new String("[");
        for(int i=0;i<arr.length;i++){
            if (i< arr.length-1){
               s=s.concat(arr[i]+" ");//返回的是一个Sring 需要s这个字符串来接受
            }else {
                s=s.concat(arr[i]+"]");
            }
        }
        return s;
    }
}

//输出结果为[Hello the World]

判断是否为大小写

if(ch>='A'&&ch<='Z') {
bigCount++;
}else if(ch>='a'&&ch<='z') {
smallCount++;
}e
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值