2011-08-25 51 views
57

如何忽略字符串的前10個字符?如何刪除字符串中的前10個字符?

輸入:

str = "hello world!"; 

輸出:

d! 
+7

string.Substring(9);其中9是開始索引 – Waqas

+0

請記住首先檢查字符串是否至少有10個字符,否則您將得到一個異常。 – Jonathan

+0

爲什麼substring不支持(startIndex,endindex)?每次我們必須計算Length .. :-( –

回答

60
str = "hello world!"; 
str.Substring(10, str.Length-10) 

您需要執行長度檢查,否則這將拋出一個錯誤

4

Substring有一個稱爲startIndex參數。根據您想要開始的索引進行設置。

1

使用子串方法。

string s = "hello world"; 
s=s.Substring(10, s.Length-10); 
+2

如果字符串比起始索引短 –

143

str = str.Remove(0,10); 刪除第10個字符

str = str.Substring(10); 創建一個子出發在字符串的第11個字符到結尾。

爲了您的目的,他們應該一致地工作。

1

您可以使用採用單個參數的方法Substring,該參數是從其開始的索引。

在我的代碼下面我處理的情況是長度小於你想要的開始索引,當長度爲零。

string s = "hello world!"; 
s = s.Substring(Math.Max(0, Math.Min(10, s.Length - 1))); 
+0

如果字符串少於10個字符,它將返回字符串中的最後一個字符。 –

12

子串可能是你想要的,正如其他人指出的那樣。但只是爲混合添加另一個選項...

string result = string.Join(string.Empty, str.Skip(10)); 

你甚至不需要檢查這個長度! :)如果少於10個字符,你會得到一個空字符串。

1

對於:

var str = "hello world!"; 

要獲得所得到的字符串沒有前10個字符和一個空字符串,如果該字符串的長度爲小於或等於10可以使用:

var result = str.Length <= 10 ? "" : str.Substring(10); 

var result = str.Length <= 10 ? "" : str.Remove(0, 10); 

第一變體是優選的,因爲它只需要一個方法參數。

0

沒有必要指定Substring方法的長度。 因此:

string s = hello world; 
string p = s.Substring(3); 

p將是:

「LO世界」。

你需要照顧是ArgumentOutOfRangeException如果 startIndex比這種情況下的長度大於小於零或唯一的例外。

1

您可以使用以下行刪除字符,

: - 首先檢查字符串中是否有足夠的字符刪除,像

string temp="Hello Stack overflow"; 
    if(temp.Length>10) 
    { 
    string textIWant = temp.Remove(0, 10); 
    } 
2

SubString有兩種重載方法:

public string Substring(int startIndex);//The substring starts at a specified character position and continues to the end of the string. 

public string Substring(int startIndex, int length);//The substring starts at a specified character position and taking length no of character from the startIndex. 

因此對於這種情況,您可以使用下面的第一種方法:

var str = "hello world!"; 
str = str.Substring(10); 

這裏的輸出是:

d! 

如果您可以通過檢查其長度適用防禦性編碼。

相關問題