【问题标题】:Optimal way to obtain substrings?获取子字符串的最佳方法?
【发布时间】:2023-03-06 14:46:01
【问题描述】:

是否有更优化的方法来获取以“,”分隔并以“。”结尾的子字符串不是这样吗?

if (paramsText != null)
   {
       while (paramsText.contains(","))
         {
            params.add(paramsText.substring(0, paramsText.indexOf(",")));
            paramsText = paramsText.substring(
                    paramsText.indexOf(",") + 1, paramsText.length());
         }

         params.add(paramsText);
   }

【问题讨论】:

  • 您的代码中没有"."

标签: java substring


【解决方案1】:

因为您实际上并没有检查“。”你可以这样做:

String[] params = paramsText.split(",");

【讨论】:

  • 有效,但是我需要稍后调用一个函数,并将参数作为 List,我将不得不循环遍历 Array 以获得等效的 List 对吗?
  • @camiloqp List l = Arrays.asList();
【解决方案2】:

也许这样的东西会适合你:

String str = "There is, a more optimal, way to obtain. subtrings which,"
           + "are separated by, and ended by. than this way.";

String[] substrings = str.split("\\s*[.,]\\s*");
for (String substr : substrings)
    System.out.println("\"" + substr + "\"");

输出:

"There is"
"a more optimal"
"way to obtain"
"subtrings which"
"are separated by"
"and ended by"
"than this way"

【讨论】:

  • 在完成String[] substrings = str.split("\\s*[.,]\\s*"); 之后,我需要将substrings 作为列表,因此我将不得不循环遍历数组,总结果会比我的原始代码更优化吗?顺便说一句,我问这个是因为此功能会将网页内容从西班牙语翻译成英语,反之亦然,谢谢
  • 如果你需要一个数组的列表接口,你可以做Arrays.asList(substrings),但我不会太担心这个小sn-p代码的性能,除非它是一个瓶颈...我的意思是,如果您的目标是通过翻译器,我敢打赌瓶颈在其他地方。
  • 谢谢,这应该至少能提高一点性能;)
猜你喜欢
  • 1970-01-01
  • 2012-11-25
  • 2019-03-03
  • 2017-05-31
  • 2011-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多