Start New Discussion within our Software Development Community

A closer look at some string methods, just having a learning experience and fun with this C# class. This program uses a simple MessageBox to display the results.

// StringMethods1.cs
// some string methods/functions and properties
// written and compiled with SnippetCompiler.exe 
// from: http://www.sliver.com/dotnet/SnippetCompiler/
// (this program uses csc.exe with the best compiler options)

using System;
using System.Windows.Forms;  // for MessageBox

namespace StringMethods
{
  class StringMethods
  {
    static void Main()
    {
      string str1, output;
      char[] characterArray;
      int pos;

      str1 = "I wish you were beer!";
      characterArray = new char[25];

      // start creating the output string
      output = "str1: \"" + str1 + "\"";

      // Length property
      output += "\nstr1 length: " + str1.Length;
      
      // IndexOf method (returns -1 if not found)
      pos = str1.IndexOf("w");
      output += "\nstr1 has a 'w' at index: " + pos;
    
      // find the next "w"
      pos = str1.IndexOf("w", pos+1);
      output += "\nstr1 has another 'w' at index: " + pos;

      // Search/Find a substring (returns True or False)
      if (str1.Contains("beer"))
        output += "\nstr1 contains 'beer' --> " + str1.Contains("beer");    
    
      // Search/Find a substring position
      pos = str1.IndexOf("beer");
      output += "\n'beer' starts at index: " + pos;
    
      // change case of string
      output += "\nLower case: " + str1.ToLower();
      output += "\nUpper case: " + str1.ToUpper();

      // indexing, loop through characters in str1 and display reversed
      output += "\nstr1 reversed: ";
      for (int i = str1.Length - 1; i >= 0; i--)
        output += str1[i];

      // Replace method
      output += "\nstr1 replace 'beer' with 'wine': ";
      output += str1.Replace("beer", "wine");

      // CopyTo method, copy characters from str1 into characterArray
      str1.CopyTo(0, characterArray, 0, 6);
      output += "\nContents of first 6 characters in array is: ";
      // display array
      for (int i = 0 ; i < characterArray.Length; i++)
        output += characterArray[i];

      MessageBox.Show(output, 
        "Looking at some string methods",
        MessageBoxButtons.OK);
    }
  }
}
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.