如何删除字符串中的前10个字符?

如何删除字符串中的前10个字符?

问题描述:

如何忽略字符串的前10个字符?如何删除字符串中的前10个字符?

输入:

str = "hello world!"; 

输出:

d! 
+7

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

+0

请记住首先检查字符串是否至少有10个字符,否则您将得到一个异常。 – Jonathan

+0

为什么substring不支持(startIndex,endindex)?每次我们必须计算Length .. :-( –

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

您需要执行长度检查,否则这将抛出一个错误

Substring有一个称为startIndex参数。根据您想要开始的索引进行设置。

使用子串方法。

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

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

str = str.Remove(0,10); 删除第10个字符

str = str.Substring(10); 创建一个子出发在字符串的第11个字符到结尾。

为了您的目的,他们应该一致地工作。

您可以使用采用单个参数的方法Substring,该参数是从其开始的索引。

在我的代码下面我处理的情况是长度小于你想要的开始索引,当长度为零。

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

如果字符串少于10个字符,它将返回字符串中的最后一个字符。 –

子串可能是你想要的,正如其他人指出的那样。但只是为混合添加另一个选项...

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

你甚至不需要检查这个长度! :)如果少于10个字符,你会得到一个空字符串。

对于:

var str = "hello world!"; 

要获得所得到的字符串没有前10个字符和一个空字符串,如果该字符串的长度为小于或等于10可以使用:

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

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

第一变体是优选的,因为它只需要一个方法参数。

没有必要指定Substring方法的长度。 因此:

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

p将是:

“LO世界”。

你需要照顾是ArgumentOutOfRangeException如果 startIndex比这种情况下的长度大于小于零或唯一的例外。

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

: - 首先检查字符串中是否有足够的字符删除,像

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

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! 

如果您可以通过检查其长度适用防御性编码。