C# String.IndexOf 方法

來源:互聯網
上載者:User
文章目錄
  • 文法
  • 說明
  • 執行個體

     轉載 。。。。。。

  String.IndexOf 方法 (value, [startIndex], [count])

  報告指定字元在此執行個體中的第一個匹配項的索引。搜尋從指定字元位置開始,並檢查指定數量的字元位置。

  參數

  value

  要尋找的 Unicode 字元。 對 value 的搜尋區分大小寫。

  startIndex(Int32)

  可選項,搜尋起始位置。不設定則從0開始。

  count(Int32)

  可選項,要檢查的字元位元。

  傳回值

  如果找到該字元,則為 value 的索引位置;否則如果未找到,則為 -1。

  IndexOf()

  尋找字串中指定字元或字串首次出現的位置,返首索引值,如:

  str1.IndexOf("字"); //尋找“字”在str1中的索引值(位置)

  str1.IndexOf("字串");//尋找“字串”的第一個字元在str1中的索引值(位置)

  str1.IndexOf("字",start,end);//從str1第start+1個字元起,尋找end個字元,尋找“字”在字串STR1中的位置[從第一個字元算起]注意:start+end不能大於str1的長度

  indexof參數為string,在字串中尋找參數字串第一次出現的位置並返回該位置。如string s="0123dfdfdf";int i=s.indexof("df");這時i==4。

  如果需要更強大的字串解析功能應該用Regex類,使用Regex對字串進行匹配。

  indexof() :在字串中從前向後定位字元和字串;所有的傳回值都是指在字串的絕對位置,如為空白則為- 1

  string test="asdfjsdfjgkfasdsfsgfhgjgfjgdddd";

  test.indexof('d') =2 //從前向後 定位 d 第一次出現的位置

  test.indexof('d',1) =2 //從前向後 定位 d 從第三個字串 第一次出現的位置

  test.indexof('d',5,2) =6 //從前向後 定位 d 從第5 位開始查,查2位,即 從第5位到第7位;

  lastindexof() :在字串中從後向前定位字元和字串;、

  用法和 indexof() 完全相同。

  下面介紹 IndexOfAny ||lastindexofany

  他們接受字元數組做為變元,其他方法同上,返回數組中任何一個字元最早出現的下標位置

  如下

  char[] bbv={'s','c','b'};

  string abc = "acsdfgdfgchacscdsad";

  Response.Write(abc.IndexOfAny(bbv))=1

  Response.Write(abc.IndexOfAny(bbv, 5))=9

  Response.Write(abc.IndexOfAny(bbv, 5, 3))=9

  lastindexofany 同上。

文法

  stringObject.indexOf(searchvalue,fromindex)

參數

描述searchvalue必需。規定需檢索的字串值。fromindex可選的整數參數。規定在字串中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字串的首字元開始檢索。
說明

  該方法將從頭到尾地檢索字串 stringObject,看它是否含有子串 searchvalue。開始檢索的位置在字串的fromindex 處或字串的開頭(沒有指定 fromindex 時)。如果找到一個 searchvalue,則返回 searchvalue的第一次出現的位置。stringObject 中的字元位置是從 0 開始的。

執行個體
  在本例中,我們將在

)
)

  
  

"Hello world!" 字串內進行不同的檢索:
  <script type="text/javascript">  var str="Hello world!"  document.write(str.indexOf("Hello") +"<br />"  document.write(str.indexOf("World") +"<br />"  document.write(str.indexOf("world"))
  </script>以上代碼的輸出:
  0-16

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.