4

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?

peter.murray.rust
  • 37,407
  • 44
  • 153
  • 217

4 Answers4

6

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

Joe
  • 41,484
  • 20
  • 104
  • 125
  • @Joe. Where is Chars - could you give an example. (I looked in http://msdn.microsoft.com/en-us/library/2839d5h5%28VS.71%29.aspx and didn't find anything) – peter.murray.rust Oct 10 '09 at 16:07
  • http://msdn.microsoft.com/en-us/library/system.text.stringbuilder_members%28VS.71%29.aspx It's a property. In C#, it's done via the indexer (e.g. mySb[idx] ) – Joe Oct 10 '09 at 16:10
2

For the third you could use the Remove method:

sb.Remove(i, 1);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

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];
        }
    }
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
0

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

codymanix
  • 28,510
  • 21
  • 92
  • 151