【问题标题】:Why subsequence(a,b).toString() is faster than substring(a,b)?为什么 subsequence(a,b).toString() 比 substring(a,b) 快?
【发布时间】:2015-01-18 08:04:15
【问题描述】:

为什么 subsequence(a,b).toString() substring(a,b) 快? 当我 将我的所有子序列转换为子字符串时,它会一直减慢到 %7。为什么会这样? 以下是我的代码;

private static String filterStr(String s)
{
    for(int a = 0; a < s.length(); a++)
    {
        int c = s.charAt(a);
        if(((c < 65) || ((c >90) &&(c < 97)) || (c > 122)))
        {
            if(c!=34 && c!=96 && c!=39)// tırnak değillerse
            {
                String temp = s.substring(0,a);
                temp+= s.subSequence(a+1,s.length());
                s = temp;
                a--;
            }
            else 
            {
                if(a !=0) // if not at the beginning
                {   
                    if(a == s.length()-1)
                        s = s.subSequence(0,s.length()-1).toString();
                    else
                        s = s.subSequence(0,s.length()-2).toString();
                }
                else 
                    s = s.subSequence(1,s.length()).toString();
            }
        }
        if(c >= 65 && c <= 90) // convert to lower case first character.
        {
            String temp = s.substring(1,s.length());
            c+=32;
            s = (char)c + temp;
        }
    }
    return s;
}

【问题讨论】:

  • Javadoc 是怎么说的?你看过String的源代码吗?

标签: java string substring subsequence


【解决方案1】:
CharSequence subSequence(int beginIndex, int endIndex) {
   return this.substring(beginIndex, endIndex);
}

这是 subSequence 方法的实现,不能更快/更慢。

【讨论】:

  • 除了subString(beingIndex, endIndex)的返回类型是String。 String 虽然实现了CharSequence..
  • 如何返回字符串(子字符串)? substring 返回字符串,函数返回类型是charsequence?
  • 我认为@Ian2thedv 的意思是String.subSequence(); 将返回CharSequence 而不是String 就像来自String.subString(); 一样
猜你喜欢
  • 2019-02-03
  • 2016-06-02
  • 2014-03-29
  • 2015-06-15
  • 2021-10-06
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 2011-05-30
相关资源
最近更新 更多