我在c#中有一个字符串,我必须在字符串中找到一个特定的单词“code”,并且必须在单词“code”之后获取剩余的字符串。
字符串是
“错误描述,代码:-1”
所以我必须在上面的字符串中找到单词代码,我必须得到错误代码。我见过正则表达式,但现在清楚地理解了。有什么简单的方法吗?
string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);
像这样的东西?
也许你应该处理失踪的情况code :
......
string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);
if (ix != -1)
{
string code = myString.Substring(ix + toBeSearched.Length);
// do something here
}
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"
您可以调整字符串以拆分 - 如果您使用"code : "
,返回数组的第二个成员 ( [1]
) 将包含"-1"
,使用您的示例。
更简单的方法(如果您唯一的关键字是 "code" )可能是:
string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
将此代码添加到您的项目中
public static class Extension {
public static string TextAfter(this string value ,string search) {
return value.Substring(value.IndexOf(search) + search.Length);
}
}
然后使用
"code : string text ".TextAfter(":")
使用indexOf()
功能
string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
//DO YOUR LOGIC
string errorCode = s.Substring(index+4);
}
string founded = FindStringTakeX("UID: 994zxfa6q", "UID:", 9);
string FindStringTakeX(string strValue,string findKey,int take,bool ignoreWhiteSpace = true)
{
int index = strValue.IndexOf(findKey) + findKey.Length;
if (index >= 0)
{
if (ignoreWhiteSpace)
{
while (strValue[index].ToString() == " ")
{
index++;
}
}
if(strValue.Length >= index + take)
{
string result = strValue.Substring(index, take);
return result;
}
}
return string.Empty;
}
string originalSting = "This is my string";
string texttobesearched = "my";
string dataAfterTextTobeSearch= finalCommand.Split(new string[] { texttobesearched }, StringSplitOptions.None).Last();
if(dataAfterTextobeSearch!=originalSting)
{
//your action here if data is found
}
else
{
//action if the data being searched was not found
}