如何在字符串中查找子字符串之前和之后 [英] how to find before and after sub-string in a string

查看:192
本文介绍了如何在字符串中查找子字符串之前和之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串说 123dance456 我需要拆分成两个字符串,包含子字符串 dance之前的第一个子字符串(即 123 )和子字符串之后跳舞(即 456 )。我需要找到它们并将它们保存在单独的字符串变量中,例如 String firstSubString = 123; 和String secondSubString = 456;

I have a string say 123dance456 which I need to split into two strings containing the first sub-string before the sub-string dance (i.e. 123) and after the sub-string dance (i.e. 456). I need to find them and hold them in separate string variables, say String firstSubString = 123; and String secondSubString = 456;.

是否有任何给定的String方法可以做到这一点?

Is there any given String method that does just that?

推荐答案

您可以使用 String.split(String regex) 。做这样的事情:

You can use String.split(String regex). Just do something like this:

String s = "123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];

请注意,如果dance发生在原始字符串中不止一次, split()将在每次出现时拆分 - 这就是返回值为数组的原因。

Please note that if "dance" occurs more than once in the original string, split() will split on each occurrence -- that's why the return value is an array.

这篇关于如何在字符串中查找子字符串之前和之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆