user2384694 user2384694 - 1 month ago 5
Java Question

Replace substring from beginning given another string

I have two strings s1 & s2. I want to remove s2 from s1 if s1 starts with s2. s2 can be of variable length.

For eg. s1 = 123456789 s2 = 123 output = 456789
For eg. s1 = 123456789 s2 = 12345 output = 6789


Right now I do index calculation for s2 from s1 and then extract the substring.

I am curious is there a better way of doing this? Regular expressions?

Answer

No sense using regex for a simple substring problem. Broken down:

//precondition: s2.length() <= s1.length()
String piece = s1.substring(0, s2.length());
String remainder = s1.substring(s2.length());
return piece.equals(s2) ? remainder : s1;

Or even shorter/simplified:

return s1.startsWith(s2) ? s1.substring(s2.length()) : s1;
Comments