我有一个txt文件作为一个字符串,我需要找到两个字符和LTRIM / RTRIM一切的话。它可以具有是有条件的,因为根据该字符串的两个字符可能会改变。
例如:
车=(之间的数据在这里我想);
汽车=(我想在这里之间的数据)LT; /值GT;
code:
INT POS = st.LastIndexOf(汽车=,StringComparison.OrdinalIgnoreCase);
如果(POS> = 0)
{
服务器= st.Substring(0,POS); ..............
}
解决方案
这是一个简单的扩展方法,我用的:
之间(此字符串SRC,串findfrom,串findto)公共静态字符串
{
INT开始= src.IndexOf(findfrom);
int值= src.IndexOf(findto,启动+ findfrom.Length);
如果(开始℃的||到< 0)返回;
字符串s = src.Substring(
启动+ findfrom.Length,
到 - 启动 - findfrom.Length);
返回S;
}
有了这个,你可以使用
字符串valueToFind = sourceString.Between(汽车=,< /值GT;)
您也可以尝试这样的:
之间(此字符串SRC,串findfrom公共静态字符串,
PARAMS字符串[] findto)
{
INT开始= src.IndexOf(findfrom);
如果(开始℃下)返回;
的foreach(在findto串STO)
{
int值= src.IndexOf(申通快递,启动+ findfrom.Length);
如果(到大于= 0)返
src.Substring(
启动+ findfrom.Length,
到 - 启动 - findfrom.Length);
}
返回 ;
}
通过这个可以给你多重结局令牌(它们的顺序很重要)
字符串valueToFind = sourceString.Between(汽车=,;,< /值GT;)
I have a txt file as a string, and I need to find words between two characters and Ltrim/Rtrim everything else. It may have to be conditional because the two characters may change depending on the string.
Example:
car= (data between here I want) ;
car = (data between here I want) </value>
Code:
int pos = st.LastIndexOf("car=", StringComparison.OrdinalIgnoreCase);
if (pos >= 0)
{
server = st.Substring(0, pos);..............
}
解决方案
This is a simple extension method I use:
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
With this you can use
string valueToFind = sourceString.Between("car=", "</value>")
You can also try this:
public static string Between(this string src, string findfrom,
params string[] findto)
{
int start = src.IndexOf(findfrom);
if (start < 0) return "";
foreach (string sto in findto)
{
int to = src.IndexOf(sto, start + findfrom.Length);
if (to >= 0) return
src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
}
return "";
}
With this you can give multiple ending tokens (their order is important)
string valueToFind = sourceString.Between("car=", ";", "</value>")