我有一个大字符串,它存储在一个字符串变量str中。我想从c#中得到一个子串?
假设字符串是:" Retrieves a substring from this instance. The substring starts at a specified character position."
我希望显示的子串结果是:The substring starts at a specified character position.
答案 0 :(得分:20)
您可以手动或使用IndexOf
方法执行此操作。
手动:
int index = 43;
string piece = myString.Substring(index);
使用IndexOf,您可以看到fullstop的位置:
int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);
答案 1 :(得分:19)
答案 2 :(得分:4)
以下是从14个字符到字符串结尾的子字符串的示例。您可以修改它以满足您的需求
string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);
答案 3 :(得分:2)
日亚
假设您想要在句号(。)上进行拆分,那么这是一种可以捕获所有出现的方法:
// add @ to the string to allow split over multiple lines
// (display purposes to save scroll bar appearing on SO question :))
string strBig = @"Retrieves a substring from this instance.
The substring starts at a specified character position. great";
// split the string on the fullstop, 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);
}
...享受
答案 4 :(得分:1)
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('.'))
这将切断位于特殊字符之间的字符串部分。
答案 5 :(得分:0)
var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";
var result = data.Split(new[] {'.'}, 1)[0];
输出:
从此实例中检索子字符串。子串从a开始 指定的角色位置。
答案 6 :(得分:0)
it's easy to rewrite this code in C#...
如果您的值在2个子串之间,则此方法有效!
例如:
stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
应该是:
myNameValue = SplitStringByASubstring(stringContent , "[myName]")
colorValue = SplitStringByASubstring(stringContent , "[color]")
etcValue = SplitStringByASubstring(stringContent , "[etc]")