java字符串分隔符截取_Java字符串的查找、截取与分割操作

查找子串可以使用indexOf()方法,截取指定字符串可以使用substring()方法,分割子串可以使用split()方法,例子如下:

public class Test {

public static void main(String[] args) {

String str="1qaz2wsxzaq12wsx";

System.out.println("查找:");

//查找指定字符第一次出现的位置,参数为字符的ascii码 a-97

int test1=str.indexOf(97);

//查找指定字符串第一次出现的位置

int test2=str.indexOf("12");

//如果要查找的不存在,indexOf()返回-1

int test3=str.indexOf("qwer",0);

System.out.println("test1="+test1);

System.out.println("test2="+test2);

System.out.println("test3="+test3);

System.out.println("截取:");

//从索引处取到末尾(不包括索引处)

String substr1=str.substring(4);

//指定索引区间(包括结束索引处)

String substr2=str.substring(5, 8);

System.out.println("substr1="+substr1);

System.out.println("substr2="+substr2);

System.out.println("分割:");

//以a为分隔符,split需要注意一下转义的情况

String[] splitstr=str.split("a");

for(String spl : splitstr){

System.out.println(spl);

}

}

}

输出如下:

查找:

test1=2

test2=11

test3=-1

截取:

substr1=2wsxzaq12wsx

substr2=wsx

分割:

1q

z2wsxz

q12wsx

再来一个这三个方法的组合操作:

如果一个字符串为http://www.baidu.com:8888,我想要获取从//到:之间的这段域名,可以这样写:

//把输出的//用split()分隔,前半部分不需要,只要后半部分,匹配到第一个冒号,然后取到中间的值

String[] split = res.split ( "\\/\\/" );

//加for循环是为了匹配多个

for (int i=1;i

String str = split[i].substring ( 0, split[i].indexOf ( ":" ) );

System.out.println ( str );

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值