Csharp/CSharp Tutorial/String/String Search

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

Search a character in a string

<source lang="csharp">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); 

 } 

}</source>

str: abcdefghijk
Index of first "h": 7

Search a character in a string: lastindex

<source lang="csharp">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); 

 } 

}</source>

str: abcdefghijk
Index of last "h": 7

Search any characters in a string

<source lang="csharp">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); 
 }

}</source>

Index of first "a", "b", or "c": 0

Search a string from the start or from the end

<source lang="csharp">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);  
     
 }   

}</source>

Index of first occurrence of One: 9
Index of last occurrence of One: 17

Search a sub string in a string

<source lang="csharp">using System;

class MainClass {

 public static void Main() { 
   string str = "abcdefghijk"; 
   int idx; 

   idx = str.IndexOf("def"); 
   Console.WriteLine("Index of first \"def\": " + idx); 
 }

}</source>

Index of first "def": 3

Search a sub string in a string: lastIndexOf

<source lang="csharp">using System;

class MainClass {

 public static void Main() { 
   string str = "abcdefghijk"; 
   int idx; 

   idx = str.LastIndexOf("def"); 
   Console.WriteLine("Index of last \"def\": " + idx); 
 }

}</source>

Index of last "def": 3

String starts with and ends with

<source lang="csharp">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.\""); 
 }

}</source>

str begins with "abc"
str ends with "ijk."