Search code examples
javastringmasking

Apply string mask


I want to apply some kind of string mask, I have two Strings, the first one is final "xx" and the second one may be one letter or two letter String, If it's just one letter (for ex.'y' ) I want the resulted String to be "xy" and if it consists of two letters (for ex. 'yz') I want the resulted String to be "yz", So, it will be like the following:

final String a = "xx";
String b = "y";
string c = "yz";

by applying the mask to (a) and (b)

String result = "xy"

by applying the mask to (a) and (c)

String result = "yz"

I know there are a lot of workarounds for that like checking string length, but I'm looking for a strait forward way to achieve that(without using if-else).


Solution

  • String xx = "xx";
    String yz = "yz"; // or "y"
    String res = (xx + yz).substring(xx.length()+yz.length() - 2);
    

    This will indeed produce "xy" or "yz" but this may be due to your selection of sample data and not work for a more general case you may have had in mind. - If so, make sure to add some explanations to your question.

    Otherwise - what's so terrible about an if statement?