C# 字串處理

來源:互聯網
上載者:User

標籤:c#   字串   string   

C# 字串處理        .NET 提供了String類和System.Text命名空間來快速實現字串處理功能。
字串比較        比較字串是指按照字典排序的規則,判斷兩個字串的大小。前面的字母要小於後面的字母。String類中,常見的比較字串的方法有Compare、CompareTo、CompareOrdinal以及Equals等。Compare方法        Compare方法是String類的靜態方法,用於全面比較兩個字串對象。包含多種重載方式:
Int Compare(string strA, string strB)Int Compare(string strA, string strB, bool ignoreCase)Int Compare(string strA, string strB, bool ignoreCase, CultureInfo)Int Compare(string strA, int indexA, string strB, int indexB, int length)Int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
        各參數的含義如下:
  • strA,strB--待比較的兩個字串;
  • ignoreCase--指定是否考慮大小寫,當取true時忽略大小寫;
  • indexA,indexB--需要比較兩個字串的子串時,indexA和indexB分別為子字串的起始位置;
  • length--待比較字串的最大長度;
  • culture--字串的地區性資訊。
        Compare方法的返回值:若strA>strB返回正整數; 若strA=strB,返回0; 若strA<strB,返回負整數。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            string strA = "你好";            string strB = "你好嗎";            // 字串比較            Console.WriteLine(string.Compare(strA, strB));            Console.WriteLine(string.Compare(strA, strA));            Console.WriteLine(string.Compare(strB, strA));        }    }}
        輸出:
        說明:CompareOrdinal方法和Compare方法非常類似,但不考慮地區性問題,下面不再詳細介紹CompareOrdinal方法。CompareTo方法        CompareTo方法將當前字串對象與另一個字串對象作比較,作用與Compare方法類似,返回值也是相同的。        CompareTo方法和Compare方法區別在於:
  1. CompareTo方法不是靜態方法,可以通過一個String對象調用;
  2. CompareTo方法沒有重載形式,只能按照大小寫敏感的方式比較兩個整串。
        下面使用CompareTo比較兩個字串:
string strA = "你好";string strB = "你好嗎";Console.WriteLine(strA.CompareTo(strB));
Equals方法        如果兩個字串相等,Equals()返回值為true;否則,返回false。
string strA = "你好";string strB = "你好嗎";Console.WriteLine(string.Equals(strA, strB));Console.WriteLine(strA.Equals(strB));
定位字元及子串




































































C# 字串處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.