如果一个单词与我比较的字符串匹配,我想看到我检查的上一个单词。听起来很难理解,所以我希望代码能够更好地解释它:
String line = "qwerty/asdfg/xxx/zxcvb";
string[] words = line.Split('/');
foreach (string word in words)
{
if (word.Contains("xxx"))
{
Console.WriteLine(word.Last);
Console.Writeline(word.Next); //It doenst work this way, but I hope you understand the idea
}
}
答案 0 :(得分:2)
您需要做的是拥有一个维持搜索当前状态的变量。在你的情况下,它非常简单,因为你要记住的是检查的最后一个单词:
string line = "qwerty/asdfg/xxx/zxcvb";
string[] words = line.Split('/');
string previousWord = "";
foreach (string word in words)
{
if (word.Contains("xxx"))
{
Console.WriteLine(previousWord);
}
previousWord = word;
}
答案 1 :(得分:2)
只需存储您选中的最后一个单词。
此外,如果您需要文化或区分大小写感知,则应使用String.IndexOf()
。
String line = "qwerty/asdfg/xxx/zxcvb";
string[] words = line.Split('/');
string previous = words.First();
string next = "";
foreach (string word in words)
{
var currentIndex = (Array.IndexOf(words, word));
if (currentIndex + 1 < words.Length)
{
next = words[currentIndex + 1];
}
if (word.IndexOf("xxx", StringComparison.CurrentCulture) > -1)
{
Console.WriteLine(previous);
if (next == word)
{
Console.WriteLine("The match was the last word and no next word is available.");
}
else
{
Console.WriteLine(next);
}
}
else
{
previous = word;
}
}
在这种特殊情况下,&#34; asdfg&#34;输出为前一个和&#34; zxcvb&#34;是下一个。但是,如果您正在寻找&#34; zxcvb&#34;作为匹配,&#34;匹配是最后一个单词,没有下一个单词可用。&#34;将输出。
答案 2 :(得分:1)
只需使用var sampleDict = ["dictionary" : [String: String]()]
sampleDict["dictionary"]?.updateValue("avalue", forKey: "akey")
sampleDict["dictionary"]?["akey"] = "avalue"
循环代替for
foreach
结果:
String line = "qwerty/asdfg/xxx/zxcvb";
string[] words = line.Split('/');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Contains("xxx"))
{
// Check to make sure you to go beyond the first element
if (i - 1 > -1)
{
// Previous word
Console.WriteLine(words[i - 1]);
}
// Check to make sure you to go beyond the last element
if (i + 1 < words.Length)
{
// Next word
Console.WriteLine(words[i + 1]);
}
}
}
Console.ReadLine();
您也可以使用asdfg
zxcvb
Array.IndexOf()
答案 3 :(得分:0)
lessc theme.less theme.css
答案 4 :(得分:-1)
单词[words.IndexOf(word) - 1]应该可以做到。
编辑:忘了这个。 Almo更好,不容易出现异常。