SubSul
SubSul

Reputation: 2563

Better string manipulation code

I'm looking for an efficient (one line) string manipulation code to achieve this, regex probably. I have a string, for example, "Calvin" and I need to convert this to "/C/a/l/Calvin". i.e. take first three characters, separate them using '/' and later append the original string.

This is the code I've come up with and its working fine, just looking for a better one.

String first = StringUtils.substring(prodName, 0, 1);
String second = StringUtils.substring(prodName, 1, 2);
String third = StringUtils.substring(prodName, 2, 3);

String prodPath = path + "/" + first + "/" + second + "/" + third + "/" + prodName + "/" ;

Upvotes: 3

Views: 222

Answers (9)

J-Alex
J-Alex

Reputation: 7107

You can use String Builder:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
    sb.append("/").append(prodName.charAt(i));
}
sb.append('/').append(prodName);

Or you can put all the code in loop:

int size = 2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= size; i++) {
    if (i == 0)
        sb.append('/');
    sb.append(prodName.charAt(i)).append("/");
    if (i == size)
        sb.append(prodName);
}

Upvotes: 0

Raedwald
Raedwald

Reputation: 48682

You said efficient but you maybe meant terse. I doubt either should be an objective, so you have a different problem.

Why do you care that this string transformation requires four lines of code? Are you concerned that something that in your mind is one operation ("create transformed string") is spread over four Java operations? You should extract the four lines of Java into their own method. Then, when you read the code where the operation is needed you have one conceptual operation ("create transformed string") corresponding to one Java operation (call a method). You could call the methid createTransformedString to make the code even clearer.

Upvotes: 0

wvdz
wvdz

Reputation: 16651

Don't use regex for simple stuff like this. You may save a couple lines, but you loose a lot in readability. Regex usually take some time to understand when reading them.

String s = path;
for (int i = 0; i < 3; i++)
    s += prodName.substring(i,i+1) + "/";
s += prodName

Upvotes: 2

Roel Strolenberg
Roel Strolenberg

Reputation: 2950

No use of a regex, but a simple split over nothing =)

String[] firstThree = prodName.split("");
String prodPath = path + "/" + firstThree[0] + "/" + firstThree[1] + "/" + firstThree[2] + "/" + prodName + "/";

Another approach is using charAt():

String prodPath = path + "/" + prodName.charAt(0) + "/" + prodName.charAt(1) + "/"+ prodName.charAt(2) + "/" + prodName + "/";

Upvotes: 0

Andreas
Andreas

Reputation: 159114

What is the point of StringUtils.substring(prodName, 0, 1) when the built-in prodName.substring(0, 1) will do the same thing??

Anyway, assuming prodName is always at least 3 characters long (since you didn't give rules for expected output if it is not), this is the fastest way to do it:

String prodPath = path + '/' +
                  prodName.charAt(0) + '/' +
                  prodName.charAt(1) + '/' +
                  prodName.charAt(2) + '/' +
                  prodName + '/';

Normally, char + char is integer addition, not string concatenation, but since the first value is a String, and the + operator is left-associative, all + operators are string concatenations, not numeric additions.

Upvotes: 4

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34217

You can use MessageFormat.format()

MessageFormat.format("{0}/{1}/{2}/{3}/{4}/", baseDir, name.charAt(0), name.charAt(1), name.charAt(2), name);

imho i would wrap it for readability,

private String getProductionDirectoryPath(String baseDir, String name) {
    return MessageFormat.format("{0}/{1}/{2}/{3}/{4}/", baseDir, name.charAt(0), name.charAt(1), name.charAt(2), name);
}

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44844

How about using String.charAt

    StringBuilder b = new StringBuilder (path);
    b.append ('/').append (prodName.charAt (0))
      .append ('/').append(prodName.charAt (1))
      .append ('/').append(prodName.charAt (2))
      .append ('/').append (prodName).append ('/');

Upvotes: 3

TheLostMind
TheLostMind

Reputation: 36304

Positive look ahead can be used

public static void main(String[] args) {
    String s = "Calvin";
    System.out.println(s.replaceAll("(?=^(\\w)(\\w)(\\w))", "/$1/$2/$3/"));
}

O/P:

/C/a/l/Calvin

Upvotes: 0

shmosel
shmosel

Reputation: 50716

prodName.replaceAll("^(.)(.)(.).*", "/$1/$2/$3/$0")

Upvotes: 4

Related Questions