Input

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] ??

我有一个不含分隔符的字符串,我想根据搜索到的字符串进行分割。我的要求是将字符串分成两部分,一部分包含没有搜索文本的字符串,另一部分包含搜索文本,如下面的———-。

 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)
{

}

解决方案:

使用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行为的扩展描述

以下是string.Split在传递一个字符串时的行为的快速表格。

/stackoverflow.coma5211728652887

给TA打赏
共{{data.count}}人
人已打赏
解决方案

为什么 std::arrays 会破坏带有类型检查的模板函数?

2022-5-14 5:00:18

解决方案

如何在JavaScript中对动态创建的对象进行样式设计?

2022-5-14 6:00:06

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索