简体   繁体   English

Java获取字符串的子字符串

[英]Java Get substring of a string

I have 2 strings as shown below: 我有2个字符串,如下所示:

String paramNum = "99999256";
String opCode = "99999";

On the String paramNum I want to extract that part of the string which appears after the string value contained in opCode 我想在String paramNum上提取字符串的一部分,该部分出现在opCode包含的字符串值opCode

So with the above example: the result should be "99999256" - "99999" = "256" . 因此,在上面的示例中:结果应为"99999256" - "99999" = "256" Parse paramNum ( 99999256 ) and reach to a position of after 99999 and then do a substring till end of the string. 解析paramNum99999256 )并到达99999之后的位置,然后执行子字符串直到字符串结尾。 But I am not sure on how to reach to that position? 但是我不确定如何达到那个位置?

Note this is only a symbolic representation of what I want to do with these strings and they do mean a subtraction on 2 int. 请注意,这仅是我要使用这些字符串做的符号表示,它们的确表示对2 int进行减法。

One way of 100+ possible ways: 100多种可能方式中的一种:

String res = paramNum.replace(opCode,"");

Visit the String API to fuel your creative fire. 访问String API激发您的创造力。

If you want to replace only first match, you can: 如果您只想替换第一个匹配项,则可以:

String res = paramNum.replaceFirst(opCode,"");

Using String#substring : 使用String#substring

int indexOfOpCode = paramNum.indexOf(opCode);
if(indexOfOpCode != -1) {
    String extractedStr = paramNum.substring(indexOfOpCode + opCode.length());
    ...
}

I came with the below: 我带来以下内容:

if (paramNum.startsWith(opCode)) { // This can be - if (paramNum.contains(opCode)) {
   String res = paramNum.substring(opCode.length(), paramNum.length());
}

Note that for my case the string that I want to find always appears at the beginning... 请注意,对于我来说,要查找的字符串始终出现在开头...

One of the way: 方式之一:

String opcode; 字符串操作码;

String res= paranum.replaceAll(opcode," "); 字符串res = paranum.replaceAll(opcode,“”);

Will replace all the occurrence of opcode string with space...whereas in place of opcode you can also give regular expression as a string... 将所有出现的操作码字符串替换为空格...代替操作码,您还可以将正则表达式作为字符串给出...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM