differences between StringBuilder in Java and C#

元气小坏坏 提交于 2019-12-12 12:06:02

问题


I am converting Java code to C#. The StringBuilder class in Java seems to have many more methods than the C# one. I am interested in (say) the Java functionality

sb.indexOf(s);
sb.charAt(i);
sb.deleteCharAt(i);

which seems to be missing in C#.

I suppose the first two could be modelled by

sb.ToString().IndexOf(s);
sb.ToString().CharAt(i);

but would the third operate on a copy of the contents of the sb rather than the actual contents?

Is there a common way of adding this functionality to all missing methods?


回答1:


You can use the Chars member collection for .charAt. Similarly, you can use .Remove(i,1) to remove a single char at position i.




回答2:


For the third you could use the Remove method:

sb.Remove(i, 1);



回答3:


You could use extension methods like the following:

    static class Extensions
    {
        public static int IndexOf(this StringBuilder sb, string value)
        {
            return sb.ToString().IndexOf(value);
        }

//if you must use CharAt instead of indexer
        public static int CharAt(this StringBuilder sb, int index)
        {
            return sb[index];
        }
    }



回答4:


StringBuilder has an indexer, that means you can simply access single characters using sb[i]



来源:https://stackoverflow.com/questions/1548296/differences-between-stringbuilder-in-java-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!