【问题标题】:Join an array of strings in Apex在 Apex 中加入字符串数组
【发布时间】:2012-02-27 12:46:46
【问题描述】:

使用 Apex,我想拆分一个字符串,然后用“AND”运算符作为分隔符重新加入它。

我成功拆分了字符串,但在重新加入时遇到了问题。

 String [] ideaSearchText = searchText.Split(' ');
 // How to rejoin the array of strings with 'AND'?

我该怎么做?

【问题讨论】:

    标签: salesforce apex-code


    【解决方案1】:

    从 v26(冬季 13)开始,您可以通过将 String[] 传递给 String.join() 来执行此操作。

    String input = 'valueOne valueTwo valueThree';
    String[] values = input.split(' ');
    String result = String.join( values, ' AND ' );
    

    匿名 Apex 输出调用 System.debug(result)

    21:02:32.039 (39470000)|EXECUTION_STARTED
    21:02:32.039 (39485000)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
    21:02:32.040 (40123000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|<init>()
    21:02:32.040 (40157000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|<init>()
    21:02:32.040 (40580000)|USER_DEBUG|[5]|DEBUG|valueOne AND valueTwo AND valueThree
    

    【讨论】:

    • 非常感谢您的回答。它帮助我走出了深水区。此外,它真的很有意义,让我更好地理解哪些实现选择会增加堆大小。
    • 注意,您似乎无法加入 Set -- 有什么建议(除了将其转换为列表)?
    【解决方案2】:

    请注意,如果字符串对象太大,您将收到异常Regex too complicated。在这种情况下,您可以执行以下操作:

    Blob blobValue = (Blob)record.get(blobField);
    
    // Truncate string then split on newline, limiting to 11 entries
    List<String> preview = blobValue.toString().substring(0,1000).split('\n', 11);
    
    // Remove the last entry, because The list’s last entry contains all 
    // input beyond the last matched delimiter.
    preview.remove(preview.size()-1);
    
    // In my use-case, I needed to return a string, and String.join() works 
    // as the reverse of split()    
    return String.join(preview, '\n');
    

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      相关资源
      最近更新 更多