-4

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

Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118

2 Answers2

2

You should consider using a REGEX solution to your problem. Using REGEX, you can check for length and location of your charactors and then act accordingly without resorting to a bunch of if-then-else statements.

Regexs are really easy to test using many online websites. Here is a good example of one:

regex tester

user2980252
  • 69
  • 1
  • 7
1
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?

laune
  • 31,114
  • 3
  • 29
  • 42