How to splice a string in java

Abdurahman Hijazi :

So if I have a string such that

String name = "Daniel";
int age = 18;

If I want to create a string username using for example the first 3 letters of the name + the age, how can I manipulate the name to get the first 3 letters?

I understand that you can do the string.split() but I don't understand how this is applicable to this scenario.

I'm sorry if this is a stupid question but as you can probably tell I'm still a noob. Thanks in advance

R.LM :

you should take a look at the substring method. here's an example:

String myString = "this is a test string";
String subString = myString(0 /* begin index included letter*/, 4 /* end index excluded letter */) => // subString is now "this"

in your case it would look like that:

public static String extractInfos(String name, int age) {
    if (name.length() >= 3) {
        return name.substring(0, 3) + String.valueOf(age);
    }
    return name + String.valueOf(age);
}

// test section
String name = "Daniel";
int age = 18;
extractInfos(name, age); // outs "Dan18"

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386082&siteId=1