Replace all instances of certain characters within a string [duplicate]

白昼怎懂夜的黑 提交于 2020-06-29 03:48:55

问题


I have a string that comes from user: Below is an exact example

var message = "You purchased $name on $date"

Am within a Firebase Listener where variable querySnapshot is carrying data, how can looop through message and replace every occurence of $ to take the variable immediately after $ eg date and make the message be like below

message = "You purchased + querySnapshot.get("name") + on querySnapShot.get("date")

Thoughts: I imagine checking through the string message and finding all occurences of $ and getting the value after them. Then replacing $value with querySnapshot(value)...if you know how how i can implement this, kindly help out.


回答1:


Not sure If this is what you are looking for

public static void main(String[] args) {
        String message  = "You purchased $name on $date";
        String[] arr = message.split(" ");

        for (int i = 0; i < arr.length; i++) {
            String s = arr[i];
            if (s.contains("$")) {
                arr[i] = "+ querySnapshot.get(" + "\"" + s.substring(1) + "\"" + ")";
            }
        }

        System.out.println(String.join(" ", arr));

    }


来源:https://stackoverflow.com/questions/62363893/replace-all-instances-of-certain-characters-within-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!