这里分享3个C#中获取字符串指定文本的方法。
第一种:传统循环遍历方式
就是最传统的基于循环遍历的方式进行指定文本的获取。
特点 : 这个复杂度为O(n),但是消耗内存较大。
代码
public string GetStrContentByForeach(string _str, string _contentStart) {
string _result = string.Empty;
string _tempStr = string.Empty;
int _endIndex = 0;
foreach (var x in _str) {
_tempStr += x;
_endIndex++;
if (_tempStr.Contains(_contentStart)) {
_endIndex = _endIndex - _contentStart.Length;
break;
}
}
_result = _str.Replace(_str.Substring(0, _endIndex), "");
_result = _result.Replace("\n", "");
return _result;
}
第二种:使用IndexOf
其实C#中的String内置了IndexOf方法来获取指定内容的指数,然后我们可以通过这个指数来获取指定内容。
特点:复杂度是O(n),但是对内存的消耗变得很小。
代码
public string GetStrContentByIndexOf(string _str, string _contentStart) {
string _result = string.Empty;
int _startIndex = _str.IndexOf("https://");
if (_startIndex != 0){
_result = _str.Substring(_startIndex).Trim();
}
return _result;
}
第三种:使用正则表达式
C#中内置了一个正则表达式的类Regex来处理正则表达式。
特点:有更好的匹配模式,但是速度较慢,而且好像存在硬编码。
代码
public string GetStrContentByExpress(string _str)
{
string _result = string.Empty;
var _regex = Regex.Match(_str, @"{指定的文本开始}[^\s]+");
if (_regex.Success){
_result = _regex.Value;
}
return _result;
}

Comments NOTHING