[英]loop through string to find substring
我有这个字符串:
text = "book//title//page/section/para";
我想通过它查找所有//和/以及它们的索引。
我尝试这样做:
if (text.Contains("//"))
{
Console.WriteLine(" // index: {0} ", text.IndexOf("//"));
}
if (text.Contains("/"))
{
Console.WriteLine("/ index: {0} :", text.IndexOf("/"));
}
我也在考虑使用:
Foreach(char c in text)
但由于//
不是一个字符,因此无法正常工作。
我怎样才能实现自己想要的?
我也尝试过这个但没有显示结果
string input = "book//title//page/section/para";
string pattern = @"\/\//";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0)
{
Console.WriteLine("{0} ({1} matches):", input, matches.Count);
foreach (Match match in matches)
Console.WriteLine(" " + input.IndexOf(match.Value));
}
先感谢您。
简单:
var text = "book//title//page/section/para";
foreach (Match m in Regex.Matches(text, "//?"))
Console.WriteLine(string.Format("Found {0} at index {1}.", m.Value, m.Index));
输出:
Found // at index 4.
Found // at index 11.
Found / at index 17.
Found / at index 25.
可以使用Split吗?
所以:
string[] words = text.Split(@'/');
然后通过单词? 由于//,您将有空格,但这可能吗?
如果您要的是列表“ book”,“ title”,“ page”,“ section”,“ para”,则可以使用split。
string text = "book//title//page/section/para";
string[] delimiters = { "//", "/" };
string[] result = text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);
System.Diagnostics.Debug.WriteLine(result);
Assert.IsTrue(result[0].isEqual("book"));
Assert.IsTrue(result[1].isEqual("title"));
Assert.IsTrue(result[2].isEqual("page"));
Assert.IsTrue(result[3].isEqual("section"));
Assert.IsTrue(result[4].isEqual("para"));
Sometin喜欢:
bool lastCharASlash = false;
foreach(char c in text)
{
if(c == @'/')
{
if(lastCharASlash)
{
// my code...
}
lastCharASlash = true;
}
else lastCharASlash = false;
}
您也可以执行text.Split(@"//")
您可以用自己的单词替换//和/ /,然后找到的最后一个索引
string s = "book//title//page/section/para";
s = s.Replace("//", "DOUBLE");
s = s.Replace("/", "SINGLE");
IList<int> doubleIndex = new List<int>();
while (s.Contains("DOUBLE"))
{
int index = s.IndexOf("DOUBLE");
s = s.Remove(index, 6);
s = s.Insert(index, "//");
doubleIndex.Add(index);
}
IList<int> singleIndex = new List<int>();
while (s.Contains("SINGLE"))
{
int index = s.IndexOf("SINGLE");
s = s.Remove(index, 6);
s = s.Insert(index, "/");
singleIndex.Add(index);
}
请记住先替换为double,否则将获得//而不是DOUBLE的SINGLESINGLE。 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.