Replace Char with String

image_pdfimage_print

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

image_pdfimage_print
   
 
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)&#039;z&#039;; i >= (int)&#039;a&#039;; i--) {
            char old1 = (char)i;
            char new1 = (char)(i + 1);
            greetingBuilder = greetingBuilder.Replace(old1, new1);
        }

        for (int i = (int)&#039;Z&#039;; i >= (int)&#039;A&#039;; i--) {
            char old1 = (char)i;
            char new1 = (char)(i + 1);
            greetingBuilder = greetingBuilder.Replace(old1, new1);
        }

        Console.WriteLine("Encoded:
" + greetingBuilder.ToString());
    }
}

    


Use StringBuilder to reverse a string

image_pdfimage_print
   
 

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

image_pdfimage_print
   
 

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."));
   }
}