我有一个大字符串,存储在一个字符串变量中,str。我想在C#中从该字符串中获取子串。
假设字符串是:" Retrieves a substring from this instance. The substring starts at a specified character position, "
我想要显示的子串结果是:The substring starts at a specified character position.
我有一个大字符串,存储在一个字符串变量中,str。我想在C#中从该字符串中获取子串。
假设字符串是:" Retrieves a substring from this instance. The substring starts at a specified character position, "
我想要显示的子串结果是:The substring starts at a specified character position.
你可以手动完成这个操作,或者使用IndexOf
方法。
手动:
int index = 43;
string piece = myString.Substring(index);
使用IndexOf方法,您可以查看句号(full stop)的位置:int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);
int index = 1+myString.IndexOf(".");string piece = myString.Substring(index);
来省略掉'.'。 - Harsh Baidstring text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
// Get substring where 14 is the start index
string substring = text.Substring(14);
// Add @ to the string to allow split over multiple lines
// (for display purposes to save the scroll bar from
// appearing on a Stack Overflow question :))
string strBig = @"Retrieves a substring from this instance.
The substring starts at a specified character position. great";
// Split the string on the full stop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
.Where(x => x.Length > 0).Select(x => x.Trim());
// Iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
Console.WriteLine(subword);
}
C# 8中使用索引的更好解决方案:
string s = " Retrieves a substring from this instance. The substring starts at a specified character position, ";
string subString = s[43..^2]; // The substring starts at a specified character position
string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";
string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))
var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";
var result = data.Split(new[] {'.'}, 1)[0];
输出:
从此实例检索子字符串。子字符串从指定的字符位置开始。
所有答案都使用了降低性能的主字符串。您应该使用Span
以获得更好的性能:
var yourStringSpan = yourString.AsSpan();
int index = yourString.IndexOf(".") + 1;
string piece = yourStringSpan.slice(index);
只是想知道经过这么多年后是否有人在寻找这个.. 你可以通过这行代码从字符串中获取所需的子串。
string text = "Retrieves a substring from this instance. The substring starts at a specified character position, ";
text = text.Substring(text.IndexOf('.') + 1);
在C#中重写这段代码很容易...
如果您的值在两个子字符串之间,此方法将起作用!
例如:
stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
调用应该是:
myNameValue = SplitStringByASubstring(stringContent, "[myName]")
colorValue = SplitStringByASubstring(stringContent, "[color]")
etcValue = SplitStringByASubstring(stringContent, "[etc]")