问题描述:

How to remove word in string array

var array= new string []

{"windows!!1!!","dual+sim!!3!!","32+gb!!2!!","Intel+i5!!2!!"};

Output array

var Output-array= new string []

{"windows","dual sim","32 gb","Intel i5"};

How can do like this in single line of code in C#

网友答案:

Assuming your pattern is always !![one digit]!!

Regex should be the easiest way to solve this. And a Replace("+", " ") to replace + characters with a space.

string[] array = new string[] { "windows!!1!!", "dual+sim!!3!!", "32+gb!!2!!", "Intel+i5!!2!!" };
string[] result = array.Select(x => System.Text.RegularExpressions.Regex.Replace(x, @"!!\d!!", "").Replace("+", " ")).ToArray();
网友答案:

While not a single liner. No need to understand RegEx,and an extension method that should be in your toolkit anyway. Only assumption is a "!!" being your terminator for the string you wish to extract.

/// <summary>
/// Get string value before [first] a.
/// </summary>
public static string Before(this string value, string a)
{
   int posA = value.IndexOf(a);
   if (posA == -1)
   {
       return "";
   }
   return value.Substring(0, posA);
}

var myList = new List<string>();
foreach var element in array
{
    myList.Add(element.Before("!!"));
}

var outPutArray = myList.ToArray();
相关阅读:
Top