using System;
using System.Text;
public class MainClass {
static String ReplaceCharString(String s, char c1, String s2) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < s.Length; i++)
if (s[i] == c1)
res.Append(s2);
else
res.Append(s[i]);
return res.ToString();
}
}
[/csharp]
Replace char in a StringBuilder object
using System; using System.Collections.Generic; using System.Text; class Program { static void Main(string[] args) { StringBuilder greetingBuilder = new StringBuilder("www.kutayzorlu.com/java2s/com"); for (int i = (int)'z'; i >= (int)'a'; i--) { char old1 = (char)i; char new1 = (char)(i + 1); greetingBuilder = greetingBuilder.Replace(old1, new1); } for (int i = (int)'Z'; i >= (int)'A'; i--) { char old1 = (char)i; char new1 = (char)(i + 1); greetingBuilder = greetingBuilder.Replace(old1, new1); } Console.WriteLine("Encoded: " + greetingBuilder.ToString()); } }
using the StringBuilder methods Replace, Insert, Append, AppendFormat, and Remove:
using System; using System.Text; class UseSBApp { static void Main(string[] args) { StringBuilder sb = new StringBuilder("Pineapple"); sb.Replace('e', 'X'); sb.Insert(4, "Banana"); sb.Append("Kiwi"); sb.AppendFormat(", {0}:{1}", 123, 45.6789); sb.Remove(sb.Length - 3, 3); Console.WriteLine(sb); } }
Use StringBuilder to reverse a string
using System; using System.Text; class MainClass { public static string ReverseString(string str) { if (str == null || str.Length <= 1) { return str; } StringBuilder revStr = new StringBuilder(str.Length); for (int count = str.Length - 1; count > -1; count--) { revStr.Append(str[count]); } return revStr.ToString(); } public static void Main() { Console.WriteLine(ReverseString("The quick brown fox jumped over the lazy dog.")); } }
Length and Indexer
using System; using System.Text; class MainClass { public static string ReverseString(string str) { if (str == null || str.Length <= 1) { return str; } StringBuilder revStr = new StringBuilder(str.Length); for (int count = str.Length - 1; count > -1; count--) { revStr.Append(str[count]); } return revStr.ToString(); } public static void Main(){ Console.WriteLine(ReverseString("Madam Im Adam")); Console.WriteLine(ReverseString("The quick brown fox jumped over the lazy dog.")); } }
Create a StringBuilder which hold 100 characters.
using System; using System.Text; class StringApp { static void Main(string[] args) { StringBuilder myBuffer = new StringBuilder("My string data"); Console.WriteLine(myBuffer.Capacity); myBuffer.Append(" contains some numerical data: "); myBuffer.AppendFormat("{0}, {1}.", 44, 99); Console.WriteLine(myBuffer.Capacity); Console.WriteLine(myBuffer); } }
Get Next Text Element
using System;
using System.Globalization;
using System.Threading;
class Class1 {
static void Main(string[] args) {
String MyStr, OutBuf;
MyStr = “The Quick programmer ran rings around the lazy manager”;
for (int k=0; k