String indexing

Lardmeister 0 Tallied Votes 223 Views Share

A quick look at finding a substring in a string and giving the position of the substring, if found. The string method IndexOf() has a number of options to explore.

// C# code to get the index of a substring in a string
// 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;

public class MyClass
{
  public static void Main()
  {
    String text = "Just a very short string";
    String space = " ";
    int pos;
    
    Console.WriteLine("Original Text = " + text);
    Console.WriteLine();
    
    pos = text.IndexOf(space);
    if (pos > 0)
      Console.WriteLine("First space in text is at index " + pos);
    else 
      Console.WriteLine("NO space in text.");
      
    pos = text.IndexOf("s");
    Console.WriteLine("The first 's' in text is at index " + pos); 
    
    pos = text.IndexOf("s", pos+1);
    Console.WriteLine("The second 's' in text is at index " + pos);
    
    pos = text.IndexOf("s", 3, 7);
    if (pos > 0)
      Console.WriteLine("The 's' between index 3 and 3+7 is at " + pos);
    else
      Console.WriteLine("No 's' between index 3 and 3+7"); 
    
    pos = text.LastIndexOf("s");
    Console.WriteLine("The last 's' in text is at index " + pos);
    
    Console.ReadKey(); // console wait, new with C# 2.0
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.