如何从c#中的字符串中获取子字符串?
我有一个大字符串,它存储在字符串变量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,您可以看到fullstop的位置:
int index = myString.IndexOf(".") + 1; string piece = myString.Substring(index);
string newString = str.Substring(0,10)
将给出前10个字符(从位置0到位置9)。
看到这里 。
这是从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);
日亚,
假设您想要在句号(。)上进行拆分,那么这是一种捕获所有出现的方法:
// 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 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); }
请享用…
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];
输出:
从此实例中检索子字符串。 子字符串从指定的字符位置开始。
在C#中重写这段代码很容易……
如果您的值在2个子串之间,则此方法有效!
例如:
stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
电话应该是:
myNameValue = SplitStringByASubstring(stringContent , "[myName]") colorValue = SplitStringByASubstring(stringContent , "[color]") etcValue = SplitStringByASubstring(stringContent , "[etc]")