替换字符串中某些字符的所有实例 [英] Replace all instances of certain characters within a string

查看:50
本文介绍了替换字符串中某些字符的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自用户的字符串:下面是一个确切的示例

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

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

在Firebase侦听器中,其中的queryQueryshot变量正在携带数据,如何遍历消息并替换$的每次出现,以在$之后立即获取变量(例如日期),并使消息如下所示?

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")

思路:我想象通过检查字符串消息并找到$的所有出现,然后获取它们之后的值.然后用querySnapshot(value)替换$ value ...如果您知道我该如何实现,请帮忙.

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.

推荐答案

不确定这是否是您要找的

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

    }

这篇关于替换字符串中某些字符的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆