用指定的字符串拆分字符串,不带分界符

时间:2020-04-23 18:06:20

标签: c#

Updated - When searched value is in middle

string text = "Trio charged over alleged $100m money laundering syndicate at Merrylands, Guildford West";
string searchtext= "charged over";
string[] fragments = text.Split(new string[] { searchtext }, StringSplitOptions.None);

    //Fragments
   //if [0] is blank searched text is in the beginning - searchedtext + [1]
  //if [1] is blank searched text is in the end - [0] + searched text
  // If searched text is in middle then both items has value - [0] + seachedtext + [1]

 //This loop will execute only two times because it can have maximum 2 values, issue will
 //come when searched value is in middle (loop should run 3 times) as for the searched value i have to apply differnt logic (like change background color of the text)
 // and dont change background color for head and tail
 //How do i insert searched value in middle of [0] and [1] ??

我有一个没有定界符的字符串,我试图根据搜索到的字符串进行拆分。我的要求是将字符串分成两部分,一部分包含没有searchtext的字符串,另一部分包含如下的searchtext-

 Original String - "Bitcoin ATMs Highlight Flaws in EU Money Laundering Rules"
    String 1 - Bitcoin ATMs Highlight Flaws in EU 
    String 2 - Money Laundering Rules

I have written below code it works for the above sample value, but it failed for 

Failed - Not returning String 1 and String 2, String is empty
string watch = " Money Laundering Rules Bitcoin ATMs Highlight Flaws in EU";
string serachetxt = "Money Laundering Rules";

这有效-

List<string> matchedstr = new List<string>();
string watch = "Bitcoin ATMs Highlight Flaws in EU Money Laundering Rules";
string serachetxt = "Money Laundering Rules";

string compa = watch.Substring(0,watch.IndexOf(serachetxt)); //It returns "Bitcoin ATMs Highlight Flaws in EU"

matchedstr.Add(compa);
matchedstr.Add(serachetxt);

foreach(var itemco in matchedstr)
{

}

4 个答案:

答案 0 :(得分:1)

您可以只考虑"Money Laundering Rules"作为分隔符。然后你可以写

string[] result = watch.Split(new string[] { searchtext }, StringSplitOptions.None);

然后您可以再次添加定界符

string result1 = result[0];
string result2 = searchtext + result[1];

答案 1 :(得分:0)

使用string.Split。

string text = "Bitcoin ATMs Highlight Flaws in EU Money Laundering Rules";
string searchtext = "Money Laundering Rules";
string[] fragments = text.Split(new string[] { searchtext }, StringSplitOptions.None);

fragments将等于:

[0] "Bitcoin ATMs Highlight Flaws in EU "
[1] ""

在连续的数组元素之间的任何地方,都会出现搜索字符串。例如:

string originaltext = string.Join(searchtext, fragments);

String.Split行为的扩展描述

这是一个字符串行为的快速表。传递字符串时会拆分。

| Input  | Split | Result Array       |
+--------+-------+--------------------+
| "ABC"  | "A"   | { "", "BC" }       |
| "ABC"  | "B"   | { "A", "C" }       |
| "ABC"  | "C"   | { "AB", "" }       |
| "ABC"  | "D"   | { "ABC" }          |
| "ABC"  | "ABC" | { "", "" }         |
| "ABBA" | "A"   | { "", "BB", "" }   |
| "ABBA" | "B"   | { "A", "", "A" }   |
| "AAA"  | "A"   | { "", "", "", "" } |
| "AAA"  | "AA"  | { "", "A" }        |

如果您查看上面的表,则数组中每个位置(在数组的两个连续元素之间)都有一个逗号,这是找到拆分字符串的位置。

如果找不到该字符串,则结果数组仅是一个元素(原始字符串)。

如果在输入字符串的开头找到拆分字符串,则将空字符串设置为结果数组的第一个元素,以表示字符串的开头。同样,如果在字符串末尾找到拆分字符串,则将空字符串设置为结果数组的最后一个元素。

此外,在输入字符串中搜索字符串的任何连续出现之间都包含一个空字符串。

在输入字符串中可以找到该字符串的位置存在重叠的情况下:(例如,在AAA上拆分AA可以拆分为AA | {{1 }}或A | A-其中AA位于输入字符串的位置0或位置1),然后使用更早的位置。 (例如AA | AA,结果为A)。

同样,不变的是,可以始终通过连接所有片段并将搜索文本的一个确切位置放置在元素之间来重建原始字符串。以下将永远是正确的:

{ "", "A" }

如果您只想第一次拆分...

您可以像这样将所有结果合并在一起:

string.Join(searchtext, fragments) == text

...或更有效的使用if (fragments.Length > 1) { fragments = new string[] { fragments[0], string.Join(searchtext, fragments.Skip(1)) }; }

的方式

如果只想查找搜索文本字符串的第一个位置,则使用String.IndexOf来获取搜索文本在输入字符串中第一个出现的位置。

这是您可以使用的完整功能

String.IndexOf

如果愿意,可以使用它来生成数组。

用法:

private static bool TrySplitOnce(string text, string searchtext, out string beforetext, out string aftertext)
{
    int pos = text.IndexOf(searchtext);
    if (pos < 0) {
        // not found
        beforetext = null;
        aftertext = null;
        return false;
    } else {
        // found at position `pos`
        beforetext = text.Substring(0, pos); // may be ""
        aftertext = text.Substring(pos + searchtext.Length); // may be ""
        return true;
    }
}

输出:

red * white or blue
red |or| white or blue

答案 2 :(得分:0)

您可以为此编写自己的扩展方法:

// Splits s at sep with sep included at beginning of each part except first
// return no more than numParts parts
public static IEnumerable<string> SplitsBeforeInc(this string s, string sep, int numParts = Int32.MaxValue)
    => s.Split(new[] { sep }, numParts, StringSplitOptions.None).Select((p,i) => i > 0 ? sep+p : p);

并用于:

foreach(var itemco in watch.SplitsBeforeInc(watch, serachetxt, 2))

在非LINQ版本中,这是相同的方法:

// Splits s at sep with sep included at beginning of each part except first
// return no more than numParts parts
public static IEnumerable<string> SplitsBeforeInc(this string s, string sep, int numParts = Int32.MaxValue) {
    var startPos = 0;
    var searchPos = 0;
    while (startPos < s.Length && --numParts > 0) {
        var sepPos = s.IndexOf(sep, searchPos);
        sepPos = sepPos < 0 ? s.Length : sepPos;
        yield return s.Substring(startPos, sepPos - startPos);
        startPos = sepPos;
        searchPos = sepPos+sep.Length;
    }
    if (startPos < s.Length)
        yield return s.Substring(startPos);
}

答案 3 :(得分:0)

您可以尝试

        string text = "Trio charged over alleged $100m money laundering syndicate at Merrylands, Guildford West";
        string searchtext = "charged over";
        searchtextPattern =  "(?=" + searchtext + ")";

        string[] fragments= Regex.Split(text, searchtextPattern);
        //fargments will have two elements here
        // fragments[0] - "Trio"
        // fragments[1] - "charged over alleged $100m money laundering syndicate at Merrylands, Guildford West"

现在,您可以再次拆分包含搜索文本的片段,在这种情况下为fragments [1]。 参见下面的代码

            var stringWithoutSearchText = fragments[1].Replace(searchtext, string.Empty);

您需要检查每个片段是否包含搜索文本。您可以在片段的foreach循环中执行此操作。在下面添加检查内容

     foreach (var item in fragments)
     { 
        if (item.Contains(searchtext))
        { 
          string stringWithoutSearchText = item.Replace(searchtext, string.Empty);
        }
     }

参考:https://stackoverflow.com/a/521172/8652887