如何忽略字符串的前10个字符?
输入:
输入:
str = "hello world!";
输出:
d!
str = "hello world!";
输出:
d!
str = str.Remove(0,10);
删除前十个字符。
或者
str = str.Substring(10);
创建一个从第11个字符到字符串结尾的子字符串。
对于您的目的,它们应该具有相同的作用。
str = "hello world!";
str.Substring(10, str.Length-10)
你需要执行长度检查,否则可能会抛出错误
像其他人指出的那样,子字符串可能是您想要的。但是,为了混合一些其他选项...
string result = string.Join(string.Empty, str.Skip(10));
你甚至不需要检查它的长度! :) 如果它少于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!
如果您可以通过检查其长度来应用防御性编码。
Substring
拥有一个名为 startIndex 的参数。将其设置为您想要开始的索引。
string temp="Hello Stack overflow";
if(temp.Length>10)
{
string textIWant = temp.Remove(0, 10);
}
从 C# 8 开始,您可以直接使用范围运算符。这是处理这种情况更高效和更好的方法。
string AnString = "Hello World!";
AnString = AnString[10..];
string s = "hello world";
s=s.Substring(10, s.Length-10);
您可以使用Substring方法,该方法接受一个参数,即要从哪个索引开始。
在下面的代码中,我处理了长度小于所需起始索引和长度为零的情况。
string s = "hello world!";
s = s.Substring(Math.Max(0, Math.Min(10, s.Length - 1)));
在使用Substring
方法时不需要指定长度。
string s = hello world;
string p = s.Substring(3);
p
将是:
"lo world".
唯一需要注意的例外情况是,如果startIndex
小于零或大于此实例的长度,则需要处理ArgumentOutOfRangeException
。