Format a string having variable identified by colon in java

Viewed 605

I have a String having a placeholder for an id value

"Input url -> "/student/:id/"

and I need to insert such a value in order to make the result look like

Output url" -> /student/230/"

can we use format() method of String, I don't want to use %d in my url, just want a way to replace :id variable.

3 Answers

If this placeholder :id is fix and only once in your String source, then you can simply replace it with a value. See this example:

public static void main(String[] args) {
    // provide the source String with the placeholder
    String source =  "/student/:id/";
    // provide some example id (int here, possibly different type)
    int id = 42;
    // create the target String by replacing the placeholder with the value
    String target = source.replace(":id", String.valueOf(id));
    // and print the result
    System.out.println(target);
}

Output:

/student/42/

You can solve this by using String.format() like below:

String output = String.format("I am Rob with StudentId %d", studentId);

Format a string having variable identified by colon in java. You cant use format() function, this should work, this formats the first word with the starting colon even if it is not always ":id"

public String updateString(oldString, stringToBeReplaced)   
        int colonIndex = oldString.indexOf(":");
        int nextWordStartingIndex = oldString.indexOf(" ", colonIndex);
        String newString = oldString.substring(0,colonIndex) + stringToBeReplaced;
        newString = nextWordStartingIndex == -1 ? newString: newString + old.substring(nextWordStartingIndex);
        return newString;
Related