获得子串的最佳方法?

时间:2011-03-01 13:19:16

标签: java substring

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

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

         params.add(paramsText);
   }

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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"