Отформатируйте строку с переменной, обозначенной двоеточием в java - PullRequest
3 голосов
/ 02 апреля 2020

У меня есть String с заполнителем для значения идентификатора

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

, и мне нужно вставить такое значение, чтобы результат выглядел как

Output url" -> /student/230/"

можем ли мы использовать метод format () для String, я не хочу использовать% d в своем URL, просто хочу заменить способ: переменная id.

Ответы [ 4 ]

5 голосов
/ 02 апреля 2020

Если этот заполнитель :id исправлен и только один раз в вашем String источнике, то вы можете просто заменить его значением. Смотрите этот пример:

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);
}

Вывод:

/student/42/
0 голосов
/ 02 апреля 2020

Если у вас есть несколько экземпляров одной и той же подстроки для замены, вы можете использовать replace . Однако если вам нужно заменить экземпляр nth, вы можете определить свою функцию, как показано ниже.

public class Main {
    public static void main(String[] args) {
        String url = "/student/:id/xyz/:id/abc/one/:id/two/three/:id/four";
        // A test id
        int id = 123;

        // Replace all occurrences of :id
        String urlAll = url.replace(":id", String.valueOf(id));
        System.out.println(urlAll);

        // Replace nth (0-based) e.g. 0th occurrence of :id
        String url0 = replaceNthSubstr(url, ":id", 0, id);
        System.out.println(url0);

        // Replace nth (0-based) e.g. 2nd occurrence of :id
        String url2 = replaceNthSubstr(url, ":id", 2, id);
        System.out.println(url2);

        // Replace nth (0-based) e.g. 3rd occurrence of :id
        String url3 = replaceNthSubstr(url, ":id", 3, id);
        System.out.println(url3);
    }

    /**
     * 
     * @param str    - The string in which substr is to be substituted with val
     * @param substr - The substring to be replaced in str
     * @param n      - The nth (0-based) substr
     * @param val    - The value to substitute substr
     * @return If the substitution is successful, a new string with substituted
     *         value will be returned. Otherwise, str will be returned.
     */
    static String replaceNthSubstr(String str, String substr, int n, int val) {
        if (str == null || substr == null) {
            return str;
        }
        String strVal = String.valueOf(val);
        int pos = -1;
        do {
            pos = str.indexOf(substr, pos + 1);
        } while (n-- > 0 && pos != -1);
        return pos != -1 ? str.substring(0, pos) + strVal + str.substring(pos + substr.length()) : str;
    }
}

Вывод:

/student/123/xyz/123/abc/one/123/two/three/123/four
/student/123/xyz/:id/abc/one/:id/two/three/:id/four
/student/:id/xyz/:id/abc/one/123/two/three/:id/four
/student/:id/xyz/:id/abc/one/:id/two/three/123/four
0 голосов
/ 02 апреля 2020

Отформатируйте строку с переменной, обозначенной двоеточием в java. Вы не можете использовать функцию format (), это должно работать, это форматирует первое слово с начальным двоеточием, даже если это не всегда ": 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;
0 голосов
/ 02 апреля 2020

Вы можете решить эту проблему, используя String.format(), как показано ниже:

String output = String.format("I am Rob with StudentId %d", studentId);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...