Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate string problem

Tags:

c#

asp.net

If I have a string variable with value as follows :-

string mystring = "TYPE1, TYPE1, TYPE2, TYPE2, TYPE3, TYPE3, TYPE4, TYPE4";

and I want to manipulate this string and make it as follows:-

string mystring = "TYPE1,TYPE2,TYPE3,TYPE4";

ie I want to just remove all the duplicates in it, how should I do it?

Please help. Thanks.

like image 893
Infinity Avatar asked Jun 29 '11 08:06

Infinity


People also ask

What are string manipulations?

String Manipulation is a class of problems where a user is asked to process a given string and use/change its data. An example question would be a great way to understand the problems that are usually classified under this category.

What is manipulate strings in Python?

String manipulation is a process of manipulating the string, such as slicing, parsing, analyzing, etc. In many different programming languages, including Python, provides string data type to work with such string manipulating, which uses different functions of the string provided by string data type “str” in Python.

What is manipulate string in Java?

String manipulation is a sequence of characters. They are widely used in Java. In java, strings are used to create objects. It is not a primitive type and is used to create and store immutable things. Simply you can take it as constant because you can't change it once created.


2 Answers

Well, here's a LINQ approach:

string deduped = string.Join(",", original.Split(',')
                                          .Select(x => x.Trim())
                                          .Distinct());

Note that I'm using Trim because your original string has a space before each item, but the result doesn't.

Distinct() doesn't actually guarantee that ordering will be preserved, but the current implementation does so, and that's also the most natural implementation. I find it hard to imagine that it will change.

If you're using .NET 3.5, you'll need a call to .ToArray() after Distinct() as there are fewer string.Join overloads before .NET 4.

like image 121
Jon Skeet Avatar answered Sep 30 '22 13:09

Jon Skeet


You can do the following:

var parts = mystring.Split(',').Select(s => s.Trim()).Distinct().ToList();
string newString = String.Join(",", parts);
like image 43
Maximilian Mayerl Avatar answered Sep 30 '22 12:09

Maximilian Mayerl