Home > Software engineering >  C# substring with multiple character
C# substring with multiple character

Time:04-01

Please find the below sample possible strings

  • Orange bhabha<<0
  • Mango>foo>>10
  • Apple Https://test.com<<5>>2
  • Grape==50
  • kiwi>>20<<5

How do we extract text only from above string list (eg: Orange bhabha,Mango>foo,Apple Https://test.com,Grape etc..). Please find the below sample my tried Codesnip

    eg:var str="Orange<<0";
    str.Split("<<")[0].Split("==")[0].Split(">>")[0];
    // Output : Orange

It is working fine, Please let me know that is there any optimal solution to solve this issue?

Input -> Desired output 
"Orange bhabha<<0" -> "Orange bhabha"
"Mango>foo>>10" -> "Mango>foo"
"Apple Https://test.com<<5>>2" -> "Apple Https://test.com"
"Grape==50" -> "Grape"
"kiwi>>20<<5" -> "Kiwi"

CodePudding user response:

cYou could use a regular expression to replace all non-letters in the string with string.Empty

string result = Regex.Replace(<THE STRING>, @"[^A-Z] ", String.Empty);

However, the above will show ALL the letters in the string so if your string was something like 'kiwi<<02>>test' it would show 'kiwitest'

After the latest revision. The following expression should work

[^a-zA-Z:/.] 

CodePudding user response:

You can use Split from string library:

string[] stringList = { "Orange bhabha<<0", "Mango>foo>>10", "Apple Https://test.com<<5>>2", "Grape ==50", "kiwi>>20<<5" };
foreach (var str in stringList)
{
   var result = str.Split(new string [] { ">>", "<<", "==" },StringSplitOptions.None)[0];
   Console.WriteLine(result);
}

One of advantages is that you can modify the separator easily.

CodePudding user response:

Also you can try this

    foreach (var item in strList)
    {
        str = str.Replace(item, string.Empty);
    }
  • Related