【问题标题】:replace one character in a string using iterated values from a string array使用字符串数组中的迭代值替换字符串中的一个字符
【发布时间】:2016-02-03 23:41:57
【问题描述】:

我想使用字符串数组中的迭代值替换字符串中的所有特定字符。

  String Sample = " Select * from table A where Id = ? or Id = ?";

  String [] args = new String[]{"12","14"}

我想替换“?”来自具有 args 值的示例字符串。 新字符串应该是这样的

  Sample = " Select * from table A where Id = 12 or Id = 14";

谁能帮我用一些java中最好的字符串替换方法

【问题讨论】:

  • 看起来您正在尝试构建 SQL 查询。这不是如何做到的,请查找 SQL 注入(您尝试做的事情很容易受到它的影响)。然后查找准备好的语句以了解如何正确执行此操作。
  • 您可以首先生成如下语句:“Select * from table A where Id = " + args[0] + " or Id = " + args[1];

标签: java android string-concatenation


【解决方案1】:

您的方法似乎误入歧途。您有一个看起来像是为准备好的语句设计的字符串,而数组是该准备好的语句的参数列表。就这样使用它。不要手动替换这些值。

使用准备好的语句也是推荐的方法,而不是使用参数格式化字符串。 您可以获得巨大的好处,例如防止 SQL 注入、类型验证和性能。

搜索使用准备好的语句。您可能需要将参数数组更改为 Object[],其中包含正确的值类型,而不是现在的字符串。

【讨论】:

  • 但是如果你真的需要生成一个自定义语句来根据 id 提取一些信息怎么办?为了安全起见,您可以尝试 parse int 。
  • @janos 你是对的,但我在特殊情况下这样做。
  • 如果您必须这样做,请非常小心。
【解决方案2】:
    String Sample = " Select * from table A where Id = ? or Id = ?";
    String[] sampleSplitted = Sample.split("");
    String [] args = new String[]{"12","14"};
    String result = "";

    int found = 0;
    for(int i=0; i < sampleSplitted.length; i++){
        String currentPart = sampleSplitted[i];

        if(currentPart.equals("?")){
            currentPart = args[found];
            found++;
        }
        result = result + currentPart;
    }

结果:

" Select * from table A where Id = 12 or Id = 14"

【讨论】:

  • 这很容易受到 SQL 注入的攻击。
  • 你对 SQL 注入是正确的。我只是用迭代的方式回答
猜你喜欢
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 2013-12-31
相关资源
最近更新 更多