c# - 有没有办法循环这段代码,但是每次给变量一个不同的字符串?
问题描述
所以我有一些代码,工作得非常好,但只有一个实例,我想让它自己提供下一组变量,直到有一组不存在的变量......当你看到它会有意义编码。该代码只是定位并告诉字符位置并将其从原始文本中摘录出来。
所以我尝试循环它,这很容易,但我不知道如何每次都更改实例
//For comparison text
string ImpureCText = "I was very <title> proud of my my my nickname throughout high school. but today I couldn’t be .any ¡ different to what my </title> nickname was kdrlfmb ksd.f gaeks fak<p1> helllo this is a pharagraph that has been been compressed down by irrelvant words and put into a list so i can compare how many times it pops up up up in the article or in tho</p1>.";// insert text file here
string parastart = "<p1>"; // need to make this so it can change to <p2>. <p3>..etc:
bool b = ImpureCText.Contains(parastart);
string paraend = "</p1>"; // need to make this so it can change to </p2>, </p3>..etc:
bool l = ImpureCText.Contains(paraend);
if (b && l)
{
int index1 = ImpureCText.IndexOf(parastart);
int index2 = ImpureCText.IndexOf(paraend);
if (index1 >= 0) //locates char position of start of pharagraph
Console.WriteLine("'{0} begins at character position {1}", parastart, index1 + 1 );
Console.WriteLine("'{0} begins at character position {1}", paraend, index2 + 1);
//string PurePCText = ImpureCText.Substring(index1, index2);
string PurePCText = ImpureCText.Substring(index2-index1);
Console.WriteLine("Over here--"+ PurePCText);
所以它基本上会通过 , , ,... 循环这段代码,直到被识别为不存在
解决方案
制作一个包含要打印的开始和结束标签的数组:
var startTags = new[] { "<p1>", "<p2>", ... };
var endTags = new[] { "</p1>", "<p2>", ... };
for (var i = 0; i < startTags.Length; i++)
{
var startTag = startTags[i];
var endTag = endTags[i];
// Do tag stuff
}
但是如果你有一个索引,你可以使用它在循环中构建标签字符串:
for (var i = 1; i <= 8; i++)
{
var startTag = $"<p{i}>";
var endTag = $"</p{i}/>";
// Do tag stuff
}
推荐阅读
- c# - WebApp.Start() 两次调用启动配置
- ios - 何时使用 AKNodeRecorder 和 AKClipRecorder
- excel - 有条件地格式化特定的小时范围
- azure-storage - LogicApp 中的 Azure 存储表连接器问题
- git - Docker Compose:无法运行 ssh:没有这样的文件或目录
- laravel-5.4 - Laravel-维护模式页面不显示
- javascript - 使用react js获取系统登录用户并显示在网页上
- python - 如何从 Python 3 中的文本文件中获取行和下一行
- javascript - ReactJS - '.env' 文件无法按预期工作
- python - 如何通过类继承实现flask restful