我有一个包含
的字符串A F C A D A B A F G H A B C D A E A X B
我想在A B之前和之后追加一个标签,如[A B]
A F C A D [A B] A F G H [A B] C D A E [A X B] J H A
在vb.net窗体中工作
答案 0 :(得分:0)
这绝对不是最优雅的解决方案,但我相信它有效:
String strInput = "A F C A D A B A F G H A B C D A E A X B J H A A C D A E X B";
StringBuilder sbOutput = new StringBuilder();
StringBuilder sbTemp = new StringBuilder();
foreach (Char ch in strInput)
{
if (ch.Equals('A'))
{
if (sbTemp.Length > 0)
{
sbOutput.Append(sbTemp.ToString());
sbTemp = new StringBuilder().Append(ch);
}
else
{
sbTemp.Append(ch);
}
}
else
{
if (sbTemp.Length > 0)
{
sbTemp.Append(ch);
if (ch.Equals('B'))
{
sbOutput.Append(String.Format("[{0}]", sbTemp.ToString()));
sbTemp = new StringBuilder();
}
}
else
{
sbOutput.Append(ch);
}
}
}
答案 1 :(得分:0)
str = str.Replace("A B", "[A B]")
答案 2 :(得分:0)
如果你有“A X B”,硬编码的“A B”替换为“[A B]”将不起作用,所以我建议一个可能的解决方案,即正则表达式:
尝试以下两种模式:
Dim pattern1 as string = @"(A)[^A]*(?=B)"
Dim str as string = Regex.Replace(inputString, pattern1, "[\1"); // make `A` to `[A` followed by a `B`
Dim pattern2 as string = @"(?<=A)[^A]*(B)"
str = Regex.Replace(str, pattern1, "\1]"); // make `B` to `B]` // make `B` to `B]` preceded by `A`
Debug.Print(str);
希望它有所帮助!