User Tools

Site Tools

blog:2023-03-17_c_memo_for_如何搜尋字串



2023-03-17 C#: Memo for 如何搜尋字串

Memo

  • 字串是否包含文字?
    • string factMessage = "Extension methods have all the capabilities of regular static methods.";
      
      // Write the string and include the quotation marks.
      Console.WriteLine($"\"{factMessage}\"");
      
      // Simple comparisons are always case sensitive!
      bool containsSearchResult = factMessage.Contains("extension");
      Console.WriteLine($"Contains \"extension\"? {containsSearchResult}");
      
      // For user input and strings that will be displayed to the end user,
      // use the StringComparison parameter on methods that have it to specify how to match strings.
      bool ignoreCaseSearchResult = factMessage.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase);
      Console.WriteLine($"Starts with \"extension\"? {ignoreCaseSearchResult} (ignoring case)");
      
      bool endsWithSearchResult = factMessage.EndsWith(".", System.StringComparison.CurrentCultureIgnoreCase);
      Console.WriteLine($"Ends with '.'? {endsWithSearchResult}");
  • 所搜尋文字在字串中的位置?
    • string factMessage = "Extension methods have all the capabilities of regular static methods.";
      
      // Write the string and include the quotation marks.
      Console.WriteLine($"\"{factMessage}\"");
      
      // This search returns the substring between two strings, so
      // the first index is moved to the character just after the first string.
      int first = factMessage.IndexOf("methods") + "methods".Length;
      int last = factMessage.LastIndexOf("methods");
      string str2 = factMessage.Substring(first, last - first);
      Console.WriteLine($"Substring between \"methods\" and \"methods\": '{str2}'");

TAGS

  • 80 person(s) visited this page until now.

Permalink blog/2023-03-17_c_memo_for_如何搜尋字串.txt · Last modified: 2023/03/17 13:21 by jethro

oeffentlich