1

I have 2 strings as shown below:

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

So with the above example: the result should be "99999256" - "99999" = "256". Parse paramNum (99999256) and reach to a position of after 99999 and then do a substring till end of the string. 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.

4 Answers 4

5

One way of 100+ possible ways:

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

Visit the String API to fuel your creative fire.

If you want to replace only first match, you can:

String res = paramNum.replaceFirst(opCode,"");
Sign up to request clarification or add additional context in comments.

6 Comments

probably easiest of 'em all.
Tricky because if opCode appears multiple times in the string, all occurrences will be replaced.
What if 99999 appears in the second half?
With replaceFirst you should use Pattern.quote just in case opCode would contain smth like a+b+c
@DmitryGinzburg Indeed. I think my answer guides OP enough. He can easily investigate and learn from here.
|
1

Using String#substring:

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

1 Comment

0

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...

Comments

0

One of the way:

String opcode;

String 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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.