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.
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.
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.
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.
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.
You can do the following:
var parts = mystring.Split(',').Select(s => s.Trim()).Distinct().ToList();
string newString = String.Join(",", parts);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With