Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 17 days ago.
Improve this question
I am using Char[] and converting it as secured string to encrypt and decrypt a string values.
Below is the code piece I am using for creating encryption key
char[] keyChars = { '1', '2', '3', '4', '5', '6', '7', '8' }; // This is in key vault now.
var _key = new SecureString();
foreach (var chars in keyChars)
{
_key.AppendChar(chars); // key length is 8
}
I have saved this key in azure key vault and fetching it and output is returned in string. Now I want to convert the string value into char[].
I tried using the code but the variable length differs. Due to this, plain text returns different value when encrypting.
string keyVaultSecret = "'1', '2', '3', '4', '5', '6', '7', '8'"; // length 38
string[] arrayString = new[] { keyVaultSecret };
var charArrayList = arrayString.Select(
str => str.ToCharArray()).ToList(); // charArrayList length is 1 here
Can somebody please help on how to convert String into Char[] without changing the variable length.
If I understood the question correctly, you may try something like this:
string keyVaultSecret = "'1', '2', '3', '4', '5', '6', '7', '8'";
var arrayString = keyVaultSecret
.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Replace('\'', ' '))
.Select(x => x.Trim());
var charArray = string.Join(string.Empty, arrayString).ToCharArray();
Related
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.
I’m working on a data entry project(visual studio windowsform) and there are two main languages that the datas have to entered in, english and arabic, i want some fields to show errorprovider if the user enters in English language in an arabic field and vice versa, is that possible?
Thanks.
Just check if all letters in the entered text are part of the english alphabet.
string text = "abc";
char[] englishAlphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
bool english = true;
foreach (char c in text.ToLower())
if (!englishAlphabet.Contains(c))
{
english = false;
break;
}
if (english)
// Do some stuff
else
// Show error
Same for the arabic alphabet.
You can do it by yourself writing logical if condition on keystroke checking for whether entered letter is of English alphabet or not. But this is not perfect solution,it wont work for other language.
You can build a function to check for arabic characters using regex:
internal bool HasArabicCharacters(string text)
{
Regex regex = new Regex(
"^[\u0600-\u06FF]+$");
return regex.IsMatch(text);
}
Or you can build a function for english characters too using regex:
internal bool HasEnglishCharacters(string text)
{
Regex regex = new Regex(
"^[a-zA-Z0-9]*$");
return regex.IsMatch(text);
}
Source: This question
And after that you can do something like this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(HasArabicCharacters(textBox1.Text) == true)
{
//have arabic chars
//delete text for example
}
else
{
//don't have arabic chars
}
}
Output:
؋ = return true;
a = return false;
ئ = return true;
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.
I have a string that represent a number like 1234567890 and I want to split this into individual digits, somehow as follows:
<div class="counter">
#if (Model.Count > 0)
{
char[] num = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }
string TotalCount = #Model.Count;
string[] TheDigit = TotalCount.Split(num);
foreach (var TheDigit in TotalCount)
{
<li>TheDigit</li>
}
}
</div>
How can I achieve this properly? Anyway my output must be something like this:
<li>1</li><li>2</li>...<li>9</li><li class="Zero">0</li>
First of all this is not view logic, IMHO, so it should not be done in the view but in the controller. Opinions may vary on this.
To the point, if you need to obtain the digits of a number, you can do it arithmetically or string-wise. String-wise you could do (assuming that normal digits occupy only a character, culture info, bla bla, turkish I, bla):
var x = "1234567";
foreach(var digit in x)
{
<li>#digit</li>
}
So you have a char[] which contains digits and you want following as result?
<li>1</li><li>2</li>...<li>9</li>
You could use...
string result = string.Concat(num.Select(c => string.Format("<li>{0}</li>", c)));
My bad: I forgot to convert to string. Anyway is working as follows:
<div>
#if (Model.Count > 0)
{
<ul class="counter clearfix">
#{
string str = Model.Count.ToString();
foreach (var TheDigit in str)
{
<li>#TheDigit</li>
}
}
</ul>
}
<div>
<span>Joburi</span>
</div>
</div>
Thank you guys
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
remove the invalid character from price
Hi friends,
i have a scenario where i have to remove the invalid character from price using c# code.
i want the regular ex to remove the character or some thing good then this.
For Ex- my price is
"3,950,000 ( Ex. TAX )"
i want to remove "( Ex. TAX )" from the price.
my scenario is that. i have to remove the any character from string except number,dot(.), and comma(,)
please help..
thanks in advance
Shivi
private string RemoveExtraText(string value)
{
var allowedChars = "01234567890.,";
return new string(value.Where(c => allowedChars.Contains(c)).ToArray());
}
string s = #"3,950,000 ( Ex. TAX )";
string result = string.Empty;
foreach (var c in s)
{
int ascii = (int)c;
if ((ascii >= 48 && ascii <= 57) || ascii == 44 || ascii == 46)
result += c;
}
Console.Write(result);
Notice that the dot in "Ex. TAX" will stay
How about this:
using System.Text.RegularExpressions;
public static Regex regex = new Regex(
"(\\d|[,\\.])*",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
//// Capture the first Match, if any, in the InputText
Match m = regex.Match(InputText);
//// Capture all Matches in the InputText
MatchCollection ms = regex.Matches(InputText);
//// Test to see if there is a match in the InputText
bool IsMatch = regex.IsMatch(InputText);
You can use LINQ
HashSet<char> validChars = new HashSet<char>(
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '.' });
var washedString = new string((from c in "3,950,000 ( Ex. TAX )"
where validChars.Contains(c)
select c).ToArray());
but the "." in "Ex. TAX" will remain.
you may use something like [^alpha] ore [^a-z]