2012-02-27 67 views
9

當我有一個字符串,我想從某個索引切換到一個新的字符串到某個索引時,我使用哪個函數?用已知的開始和結束索引剪切一個字符串

+10

你在問之前是否搜索過這個?你到目前爲止嘗試了什麼? – 2012-02-27 17:00:02

+9

我不知道爲什麼這會降低和關閉,因爲這是MSDN文檔中找不到的真正問題。他不查找startIndex + count,而是查找startIndex + endIndex。 – Veehmot 2014-03-28 03:59:27

+1

不是一個真正的問題?是啊,就是!我發現它,因爲我有同樣的問題。親愛的casperOne:WT ??? – steve 2016-06-17 15:49:14

回答

-9

您使用String.Substring

public string Substring(
    int startIndex, 
    int length 
) 

說句公道話,這是一個比基本問題少,具有非常接近的答案 - 我給你,你試過東西懷疑的好處,它碰巧你在這裏發現它莫名其妙地;也許其他人可以受益(雖然我希望沒有多少需要它)。

+23

Downvoted。這不是OP正在尋找的東西。他正在尋找獲取字符串的一部分,該字符串知道startIndex和endIndex(與該長度不一樣)。像ECMAScript substr()函數(NOT substring()函數)。 – Veehmot 2014-03-28 03:57:36

37

如果endIndex指向你想要已包括在提取的子字符串的最後一個字符:

int length = endIndex - startIndex + 1; 
string piece = s.Substring(startIndex, length); 

如果endIndex指向第一個字符後的期望子(即的開始剩餘的文本):

int length = endIndex - startIndex; 
string piece = s.Substring(startIndex, length); 

小號ee String.Substring Method (Int32, Int32)爲MSDN上的官方說明。

1

有兩路到子字符串..

1)

public string Substring(
    int startIndex 
) 

檢索從這個實例子。子字符串從指定的字符位置開始。

2)

public string Substring(
    int startIndex, 
    int length 
) 

檢索從此實例的子串。子字符串從指定的字符位置開始並具有指定的長度。

+4

他想提供startIndex和endIndex。子串需要開始和長度。 – Chet 2016-11-07 17:34:28

相關問題