第四课、字符串相关操作

1、申明字符串变量
String str=“hello”;


2、创建字符串
(1)char=a[’h’,’e’,’l’,’l’,’o’];
String s=new String(a); //等同于String s=new String(“hello”);
(2)char=a[’h’,’e’,’l’,’l’,’o’];
String s=new String(a,0,3); // String s=new String(“hel”);


3、(1)连接字符串
string str=str1+str2;
(2)连接字符串与其他数据类型
int a=23;
string str=str1+a;
只要“+”运算符的一个操作符是字符串,编译器会将另一个操作数转换为字符产形式(调用相应的toString方法)


4、获取字符串长度
str.length();


5、字符串查找
(1)str.indexOf(substr s) //参数字符串s在字符串str中首次出现的索引位置。
(2)str.lastindexOf(substr) //参数字符串s在字符串str中最后一次出现的索引位置。


6、获取指定索引位置的字符
str.charAt(int index)


7、获取子字符串
(1)str.substring(int beginindex) //从某个位置开始的字符串
(2)str.substring(int beginindex,int endindex) //从某一个位置到另一个位置的子串。


8、去除空格
str.trim();


9、字符串替换
str.repalce(cha oldchar,char newchar);
oldchar:要替换的字符或者字符串。
newchar:用于替换的字符串
例:string str=”hello”;
string newstr=str.replace(“h”,”H”); //输出Hello


10、判断字符串的开始与结尾
(1)判断字符串是否已a开头
str.startswith(string a);
(2)判断字符串是否已b结尾
str.endswith(string b);

11、判断字符串相等
(1)equals() //区分大小写的比较。
(2)equalsIgnoreCase() //不区分大小写的比较。


12、按字典顺序比较两个字符串
str.compareTo(string other)
相等谓0,大于为整数,小于为负数。


13、字母大小写转换
(1)toLowerCase()
(2)toUpperCase()


14、字符串分隔
(1)split(string sign)
sign:分隔字符串的分隔符(可以使用“|”来指定多个),可以是正则表达式
(2)split(string sign,int linit)
linit:为分隔后字符串个数。

System.out.println("*********************");
        String testsplit="pas.df.ghj+kl";

        String[] res=testsplit.split("\\.|\\+");
        for (String a1 : res) {
            System.out.println(a1);
        }
        System.out.println("*********************");
        String testsplit1="pas.df.ghj+kl";
        String[] res1=testsplit1.split("\\.|\\+",3);
        for (String a1 : res1) {
            System.out.println(a1);
        }

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值