How to create char array of letters from a string array ? (C#) - c#

For example, I have a string:
"Nice to meet you"
, there are 13 letters when we count repeating letters, but I wanna create a char array of letters from this string without repeating letters, I mean for the string above it should create an array like
{'N', 'i', 'c', 'e', 't', 'o', 'y', 'u', 'm'}
I was looking for answers on google for 2 hours, but I found nothing, there were lots of answers about strings and char arrays, but were not answers for my situation. I thought that I can write code by checking every letter in the array by 2 for cycles but this time I got syntax errors, so I decided to ask.

You can do this:
var foo = "Nice to meet you";
var fooArr = s.ToCharArray();
HashSet<char> set = new();
set.UnionWith(fooArr);
//or if you want without whitespaces you could refactor this as below
set.UnionWith(fooArr.Where(c => c != ' '));
UPDATE:
You could even make an extension method:
public static IEnumerable<char> ToUniqueCharArray(this string source, char? ignoreChar)
{
var charArray = source.ToCharArray();
HashSet<char> set = new();
set.UnionWith(charArray.Where(c => c != ignoreChar));
return set;
}
And then you can use it as:
var foo = "Nice to meet you";
var uniqueChars = foo.ToUniqueCharArray(ignoreChar: ' ');
// if you want to keep the whitespace
var uniqueChars = foo.ToUniqueCharArray(ignoreChar: null);

this piece of code does the job:
var sentence = "Nice To meet you";
var arr = sentence.ToLower().Where(x => x !=' ' ).ToHashSet();
Console.WriteLine(string.Join(",", arr));
I have added ToLower() if you dont do differences between uppercase and lowercase, if case is sensitive you just put off this extension..
HashSet suppresses all duplicates letters
test: Fiddle

I tried this one and it works too
"Nice to meet you".Replace(" ", "").ToCharArray().Distinct();

A very short solution is to use .Except() on the input string:
string text = "Nice to meet you";
char[] letters = text.Except(" ").ToArray();
Here, .Except():
translates both the text string and the parameter string (" ") to char collections
filters out all the chars in the text char collection that are present in the parameter char collection
returns a collection of distinct chars from the filtered text char collection
Example fiddle here.
Visualizing the process
Let's use the blue banana as an example.
var input = "blue banana";
input.Except(" ") will be translated to:
{ 'b', 'l', 'u', 'e', ' ', 'b', 'a', 'n', 'a', 'n', 'a' }.Except({ ' ' })
Filtering out all ' ' occurrences in the text char array produces:
{ 'b', 'l', 'u', 'e', 'b', 'a', 'n', 'a', 'n', 'a' }
The distinct char collection will have all the duplicates of 'b', 'a' and 'n' removed, resulting in:
{ 'b', 'l', 'u', 'e', 'a', 'n' }

ToCharArray method of string is only thing you need.
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
string str = "Nice to meet you";
char[] carr = str.ToCharArray();
for(int i = 0; i < carr.Length; i++)
Console.WriteLine (carr[i]);
}
}

String str = "Nice To meet you";
char[] letters = str.ToLower().Except(" ").ToArray();

A solution just using for-loops (no generics or Linq), with comments explaining things:
// get rid of the spaces
String str = "Nice to meet you".Replace(" ", "");
// a temporary array more than long enough (we will trim it later)
char[] temp = new char[str.Length];
// the index where to insert the next char into "temp". This is also the length of the filled-in part
var idx = 0;
// loop through the source string
for (int i=0; i<str.Length; i++)
{
// get the character at this position (NB "surrogate pairs" will fail here)
var c = str[i];
// did we find it in the following loop?
var found = false;
// loop through the collected characters to see if we already have it
for (int j=0; j<idx; j++)
{
if (temp[j] == c)
{
// yes, we already have it!
found = true;
break;
}
}
if (!found)
{
// we didn't already have it, so add
temp[idx] = c;
idx+=1;
}
}
// "temp" is too long, so create a new array of the correct size
var letters = new char[idx];
Array.Copy(temp, letters, idx);
// now "letters" contains the unique letters
That "surrogate pairs" remark basically means that emojis will fail.

Related

How to remove a charlist from a string

How can I remove a specific list of chars from a string?
For example I have the string Multilanguage File07 and want to remove all vowels, spaces and numbers to get the string MltlnggFl.
Is there any shorter way than using a foreach loop?
string MyLongString = "Multilanguage File07";
string MyShortString = MyLongString;
char[] charlist = new char[17]
{ 'a', 'e', 'i', 'o', 'u',
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '0', ' ' };
foreach (char letter in charlist)
{
MyShortString = MyShortString.Replace(letter.ToString(), "");
}
Use this code to replace a list of chars within a string:
using System.Text.RegularExpressions;
string MyLongString = "Multilanguage File07";
string MyShortString = Regex.Replace(MyLongString, "[aeiou0-9 ]", "");
Result:
Multilanguage File07 => MltlnggFl
Text from which some chars should be removed 12345 => Txtfrmwhchsmchrsshldbrmvd
Explanation of how it works:
The Regex Expression I use here, is a list of independend chars defined by the brackets []
=> [aeiou0-9 ]
The Regex.Replace() iterates through the whole string and looks at each character, if it will match one of the characters within the Regular Expression.
Every matched letter will be replaced by an empty string ("").
How about this:
var charList = new HashSet<char>(“aeiou0123456789 “);
MyLongString = new string(MyLongString.Where(c => !charList.Contains(c)).ToArray());
Try this pattern: (?|([aeyuio0-9 ]+)). Replace it with empty string and you will get your desird result.
I used branch reset (?|...) so all characters are captured into one group for easier manipulation.
Demo.
public void removeVowels()
{
string str = "MultilanguAge File07";
var chr = str.Where(c => !"aeiouAEIOU0-9 ".Contains(c)).ToList();
Console.WriteLine(string.Join("", chr));
}
1st line: creating desire string variable.
2nd line: using linq ignore vowels words [captital case,lower case, 0-9 number & space] and convert into list.
3rd line: combine chr list into one line string with the help of string.join function.
result: MltlnggFl7
Note: removeVowels function not only small case, 1-9 number and empty space but also remove capital case word from string.

Count and replace all vowels in a textbox

I need to count all vowels and replace it with the letter x, in a textbox. I managed to do the counting part and here's the code, but i'm having problem with replacing all vowels in the textbox with the letter x. Can someone help me?
int total = 0;
string sentence = textBox1.Text.ToLower();
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'y'};
{
total++;
}
total = sentence.Count(c => vowels.Contains(c));
MessageBox.Show("There are " + total++ " vowels";
for (int i = 0; i < sentence.Length; i++)
EDIT 1:
Thank you all for helping. For some reason the vowels in my textbox doesnt change!!! It does the counting but no replacement of the letter x. I've tried all the solutions here, but still nothing happens to my the vowels in the textbox.
foreach(char vowel in vowels)
sentence = sentence.Replace(vowel, 'x');
For some reason the vowels in my textbox doesnt change!!! It does the
counting but no replacement of the letter x. I've tried all the
solutions here, but still nothing happens to my the vowels in the
textbox.
The textbox and the string are not linked with each other. So if you change the string you won't change the TextBox.Text. You have to re-assign the new value:
textBox1.Text = sentence; // after you have used Replace like shown above
You can use Linq:
sentence = string.Concat(sentence.Select(c => vowels.Contains(c) ? 'x' : c));
Just a simple regex:
var r = new Regex("[aeiouy]");
sentence = r.Replace(sentence, "x");
EDIT: As strings are immutable changes to sentence are not reflected in your textbox, so you have to re-assign its value:
textBox1.Text = sentence;
Try to use a ForEach Linq-Expression and string.Replace method:
vowels.ToList().ForEach(vowel => sentence = sentence.Replace(vowel, 'x'));
EDIT 1:
You could also try a for-loop as you also tried in your question:
for (int i = 0; i < sentence.Length; i++) {
if(vowels.Contains((char)sentence[i])) {
sentence[i] = 'x';
}
}
EDIT 2:
To write the value of sentence back to the TextBox add the following:
textBox1.Text = sentence;
Why not maybe simply try with a regular expresion, as the colleague above has already suggested?
Something like:
string text = "Here comes some text";
string vowels = #"([aeiou])";
Regex regex = new Regex(vowels);
Match match = regex.Match(text);
and then maybe continue your logic with some collection and a foreach cycle()in wich you do the replacing with a char/string "x".

Simplest way to split a string to a char array

Is there simplest way to split the word/sentence into every single char and store into array?
Eg:
Me and you.
array = { 'M', 'e', ' ', 'a', 'n', 'd', ' ', 'y', 'o', 'u', '.' };
Well, this is pretty simple :
"Me and you".ToCharArray();
Using String.ToCharArray Method
https://msdn.microsoft.com/en-us/library/ezftk57x(v=vs.110).aspx
var chars = "Me and you.".ToCharArray();
This might be helpful
// Input string.
string value = "Me and you.";
// Use ToCharArray to convert string to array.
char[] array = value.ToCharArray();

Checking if any words do not contain a vowel in a array by using linq

I'am tring to Check if any words do not contain a vowel. The answer that I'am expecting is yes or no.
Thes is my code:
string sentence = "I'm thinking about buying a house in the mountains.";
string[] words = sentence.Split(' ');
//1. Check if any words do not contain a vowel
IEnumerable<string> query1 = words
.Where(n => !n.Contains("a")
|| !n.Contains("e")
|| !n.Contains("o")
|| !n.Contains("i")
|| !n.Contains("r"));
How do I get the answer?
You want to use && instead of || and then you can simply use the Any method like this:
bool some_words_do_not_have_a_vowel = words
.Where(n => !n.Contains("a") && !n.Contains("e") && !n.Contains("o") && !n.Contains("i") && !n.Contains("r"))
.Any();
You can get rid of Where in this case like this:
bool some_words_do_not_have_a_vowel =
words
.Any(n => !n.Contains("a") && !n.Contains("e") && !n.Contains("o") && !n.Contains("i") && !n.Contains("r"));
Please note that this is case sensitive. You might want to do case-insensitive search instead.
By the way, r is not a vowel.
To get collection of words without vowels, you could have a collection of vowels to be checked against:
var vowels = new char[] { 'a', 'i', 'u', 'e', 'o', 'A', 'I', 'U', 'E', 'O' };
And then you check each string (word) if a word contains any vowel in the collection. You only take the words which do not contain any vowel:
var query = words.Where(x => !x.ToCharArray().Any(c => vowels.Contains(c)); //get words without vowels.
If you want to check if any of the words have vowels from all your collections. Simply use the query result with Any:
bool result = query.Any();
Or you could even check the result based on your original string.

How to convert part of a char array to a string

I want to convert part of a char array to a string. What is the best way to do that.
I know I can do the following for the whole array
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
but what about just elements 2 to 4 for example?
I also know I can loop through the array and extract them, but I wondered if there was a more succinct way of doing it.
Use the String constructor overload which takes a char array, an index and a length:
String text = new String(chars, 2, 3); // Index 2-4 inclusive
You may use LINQ
char[] chars = { 'a', ' ', 's', 't', 'r', 'i', 'n', 'g' };
string str = new string(chars.Skip(2).Take(2).ToArray());
But off course string overloaded constructor is the way to go

Categories