Csharp/CSharp Tutorial/String/String Search — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 12:16, 26 мая 2010

Search a character in a string

using System; 
 
class MainClass { 
  public static void Main() { 
    string str = "abcdefghijk"; 
    int idx; 
 
    Console.WriteLine("str: " + str); 
 
    idx = str.IndexOf("h"); 
    Console.WriteLine("Index of first "h": " + idx); 
 
  } 
}
str: abcdefghijk
Index of first "h": 7

Search a character in a string: lastindex

using System; 
 
class MainClass { 
  public static void Main() { 
    string str = "abcdefghijk"; 
    int idx; 
 
    Console.WriteLine("str: " + str); 
 
    idx = str.LastIndexOf("h"); 
    Console.WriteLine("Index of last "h": " + idx); 
 
  } 
}
str: abcdefghijk
Index of last "h": 7

Search any characters in a string

using System; 
 
class MainClass { 
  public static void Main() { 
    string str = "abcdefghijk"; 
    int idx; 
 
    char[] chrs = { "a", "b", "c" }; 
    idx = str.IndexOfAny(chrs); 
    Console.WriteLine("Index of first "a", "b", or "c": " + idx); 
  }
}
Index of first "a", "b", or "c": 0

Search a string from the start or from the end

using System;  
  
class MainClass {   
  public static void Main() {   
    string str1 = "ABCDEabcde1234567e890";   
  
    // search string 
    int idx = str1.IndexOf("e");  
    Console.WriteLine("Index of first occurrence of One: " + idx);  
    idx = str1.LastIndexOf("e");  
    Console.WriteLine("Index of last occurrence of One: " + idx);  
      
  }   
}
Index of first occurrence of One: 9
Index of last occurrence of One: 17

Search a sub string in a string

using System; 
 
class MainClass { 
  public static void Main() { 
    string str = "abcdefghijk"; 
    int idx; 
 
    idx = str.IndexOf("def"); 
    Console.WriteLine("Index of first \"def\": " + idx); 
  }
}
Index of first "def": 3

Search a sub string in a string: lastIndexOf

using System; 
 
class MainClass { 
  public static void Main() { 
    string str = "abcdefghijk"; 
    int idx; 
 
    idx = str.LastIndexOf("def"); 
    Console.WriteLine("Index of last \"def\": " + idx); 
  }
}
Index of last "def": 3

String starts with and ends with

using System; 
 
class MainClass { 
  public static void Main() { 
    string str = "abcdefghijk"; 
    if(str.StartsWith("abc")) 
      Console.WriteLine("str begins with \"abc\""); 
 
    if(str.EndsWith("ijk")) 
      Console.WriteLine("str ends with \"ijk.\""); 
  }
}
str begins with "abc"
str ends with "ijk."