问题
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