1

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#

1
  • @MaciejLos : Not any idea how to do Commented Jul 13, 2016 at 6:20

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

3 Comments

better replace the pattern with @"!!.*!!" nice answer though
yes but you should ask a new question for that, that has nothing to do with the initial question
Please reply buddy :(
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.