Split and remove duplicate from String
I want to split the given string and remove the duplicate from that string. Like I have following string:
This is my first post in stack overflow, I am very new in development and 开发者_运维技巧I did not have much more idea about the how to post the question.
Now I want to split that whole string with white space and that new array will did not have duplicate entry.
How can I do this?
"This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question."
.Split() // splits using all white space characters as delimiters
.Where(x => x != string.Empty) // removes an empty string if present (caused by multiple spaces next to each other)
.Distinct() // removes duplicates
Distinct()
and Where()
are LINQ extension methods, so you must have using System.Linq;
in your source file.
The above code will return an instance of IEnumerable<string>
. You should be able to perform most operations required using this. If you really need an array, you can append .ToArray()
to the statement.
add the array into a HashSet<String>
, this would remove the duplicates.
here is Micorosft documentation on HashSet..
static void Main()
{
string str = "abcdaefgheijklimnop";
char[] charArr = str.ToCharArray();
int lastIdx = 0;
for (int i = 0; i < str.Length;)
{
for (int j = i + 1; j < str.Length - 1; j++)
{
if (charArr[i] == charArr[j])
{
//Console.WriteLine(charArr[i]);
int idx = i != 0 ? i - 1 : i;
lastIdx = j;
string temp = str.Substring(idx, j - idx);
Console.WriteLine(temp);
break;
}
}
i++;
}
Console.WriteLine(str.Substring(lastIdx));
}
精彩评论