How to output unique symbols except case c# without LINQ - c#

Output unique symbols ignoring case
IDictionary<char, int> charDict = new Dictionary<char, int>();
foreach (var ch in text)
{
if (!charDict.TryGetValue(ch, out n)) {
charDict.Add(new KeyValuePair<char, int>(ch, 1));
} else
{
charDict[ch]++;
}
}
Appellodppsafs => Apelodsf
And Is it possible not to use LINQ?

Use a HashSet<char> to remember existing characters (that's what Distinct() does internally)
Assuming your input and expected result are type string
string input = "Appellodppsafs";
HashSet<char> crs = new HashSet<char>();
string result = string.Concat(input.Where(x => crs.Add(char.ToLower(x)))); //Apelodsf

You can try this (if you do not have long strings or performance issues):
string str = "Appellodppsafs";
string result = string.Concat(str.Select(s => $"{s}")
.Distinct(StringComparer.InvariantCultureIgnoreCase));
Console.WriteLine(result);
Output:
Apelodsf

Related

Regex alternative for extracting numeric and non-numeric strings

Using the below expression, I'm able to get the expected output and extract numbers or string and split to a string array.
Regex _re = new Regex(#"(?<=\D)(?=\d)|(?<=\d)(?=\D)", RegexOptions.Compiled);
_re.Split("2323dfdf233fgfgfg ddfdf334").Dump(); //string can be any alphanumeric start with
How to achieve the same thing without using Regex? Do I need to parse each char and segregate? I have a large array of text which needs to be processed to extract but I cannot use regex as inputs provided.
For a Linq solution, you can combine the use of Enumerable.Skip() and Enumerable.TakeWhile() while checking for char.IsDigit() to determine whether the character is a digit or not. For example:
string inputString = "2323dfdf233fgfgfg ddfdf334";
var list = new List<string>();
int usedLength = 0;
while (usedLength < inputString.Length)
{
bool isDigit = char.IsDigit(inputString[usedLength]);
string item = string.Concat(inputString.Skip(usedLength).
TakeWhile((c) => char.IsDigit(c) == isDigit));
usedLength += item.Length;
list.Add(item);
};
Then you can easily iterate through the list:
foreach (string item in list)
Console.WriteLine(item);
Output:
2323
dfdf
233
fgfgfg ddfdf
334
This solution is fast enough. Check with larger strings.
string str = "2323dfdf233fgfgfg ddfdf334";
var strings = new List<string>();
var sb = new StringBuilder();
var lastCharIsNumber = char.IsDigit(str[0]);
foreach (var c in str) {
if (char.IsDigit(c) ) {
if (!lastCharIsNumber) {
strings.Add(sb.ToString());
sb.Clear();
}
lastCharIsNumber = true;
}
else {
if (lastCharIsNumber) {
strings.Add(sb.ToString());
sb.Clear();
}
lastCharIsNumber = false;
}
sb.Append(c);
}
strings.Add(sb.ToString());
strings.Dump();

C# Sort Lithuanian Letters

I need sort letters from file as alphabet. How can i do this? I need ToString method. Now console prints:
ABCDEFGIJKLM...ĄČĖĮ...
I need to get this:
AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ
Thanks
static char[] Letters(string e) //
{
e = e.ToUpper();
char[] mas = new char[32];
int n = 0;
foreach (char r in e)
if (Array.IndexOf(mas, r) < 0)
if (Char.IsLetter(r))
mas[n++] = r;
Array.Resize(ref mas, n);
Array.Sort(mas);
return mas;
}
You can solve this by sorting the characters using a comparer that understands how to compare characters alphabetically (the default is ordinal comparison).
This implementation is very inefficient, because it converts chars to strings every time it does a compare, but it works:
public class CharComparer : IComparer<char>
{
readonly CultureInfo culture;
public CharComparer(CultureInfo culture)
{
this.culture = culture;
}
public int Compare(char x, char y)
{
return string.Compare(new string(x, 1), 0, new string(y, 1), 0, 1, false, culture);
}
}
(Note: The culture is not actually necessary here; it works without it. I just included it for completeness.)
Then you can use that with sort functions that accept anIComparer, such as Array.Sort():
static void Main()
{
var test = "AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ".ToCharArray();
Console.OutputEncoding = System.Text.Encoding.Unicode;
Array.Sort(test);
Console.WriteLine(new string(test)); // Wrong result using default char comparer.
Array.Sort(test, new CharComparer(CultureInfo.GetCultureInfo("lt"))); // Right result using string comparer.
Console.WriteLine(new string(test));
}
An alternative approach is to use an array of single-character strings rather than an array of chars, and sort that instead. This works because the sort functions will use the string comparer, which understands alphabetical order:
var test = "AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ".Select(x => new string(x, 1)).ToArray();
Console.OutputEncoding = System.Text.Encoding.Unicode;
Array.Sort(test); // Correct result because it uses the string comparer, which understands alphabetical order.
Console.WriteLine(string.Concat(test));
Or using Linq:
var test = "AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ".Select(x => new string(x, 1)).ToArray();
Console.OutputEncoding = System.Text.Encoding.Unicode;
// Correct result because it uses the string comparer, which understands alphabetical order.
test = test.OrderBy(x => x).ToArray();
Console.WriteLine(string.Concat(test));
Using an array of strings instead of an array of chars is probably more performant when sorting like this.
You could use following method to remove diacritics:
static string RemoveDiacritics(string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
Then you can use those chars for the ordering:
string e = "ABCDEFGIJKLM...ĄČĖĮ...";
var normalizedCharList = e.Zip(RemoveDiacritics(e), (chr, n) => new { chr, normValue = (int)n }).ToList();
var orderedChars = normalizedCharList.OrderBy(x => x.normValue).Select(x => x.chr);
string ordered = new String(orderedChars.ToArray());

Removing matching characters between two strings

I want to remove the characters which are matching between the two given strings. Eg.
string str1 = "Abbbccd";
string str2 = "Ebbd";
From these two strings I want the output as:
"Abcc", only those many matching characters should be removed from str1,which are present in str2.
I tried the following code:
public string Sub(string str1, string str2)
{
char[] arr1 = str1.ToCharArray();
char[] arr2 = str2.ToCharArray();
char[] arrDifference = arr1.Except(arr2).ToArray();
string final = new string(arrDifference);
return final;
}
With this code I get the output as "Ac". It removes all the matching characters between two arrays and stores 'c' only once.
First create this helper method:
IEnumerable<Tuple<char, int>> IndexDistinct(IEnumerable<char> source)
{
var D = new Dictionary<char, int>();
foreach (var c in source)
{
D[c] = D.ContainsKey(c) ? (D[c] + 1) : 0;
yield return Tuple.Create(c, D[c]);
}
}
It converts a string "aabcccd" to [(a,0),(a,1),(b,0),(c,0),(c,1),(c,2),(d,0)]. The idea is to make every character distinct by adding a counting index on equal characters.
Then modify your proposed function like this:
string Sub(string str1, string str2)
{
return new string(
IndexDistinct(str1)
.Except(IndexDistinct(str2))
.Select(x => x.Item1)
.ToArray());
}
Now that you are doing Except on Tuple<char, int> instead of just char, you should get the behavior you specified.
You can do it with lists as well:
List<char> one = new List<char>("Abbbccd".ToCharArray());
List<char> two = new List<char>("Ebbd".ToCharArray());
foreach (char c in two) {
try { one.RemoveAt(one.IndexOf(c)); } catch { }
}
string result = new string(one.ToArray());
Use C#'s string commands to modify the string.
public string testmethod(string str1, string str2)
{
string result = str1;
foreach (char character in str2.ToCharArray())
{
result = result.Replace(character.ToString(), "");
}
return result;
}

C# Reading particular values in a string

I have the following line from a string:
colors numResults="100" totalResults="6806926"
I want to extract the value 6806926 from the above string
How is it possible?
So far, I have used StringReader to read the entire string line by line.
Then what should I do?
I'm sure there's also a regex, but this string approach should work also:
string xmlLine = "[<colors numResults=\"100\" totalResults=\"6806926\">]";
string pattern = "totalResults=\"";
int startIndex = xmlLine.IndexOf(pattern);
if(startIndex >= 0)
{
startIndex += pattern.Length;
int endIndex = xmlLine.IndexOf("\"", startIndex);
if(endIndex >= 0)
{
string token = xmlLine.Substring(startIndex,endIndex - startIndex);
// if you want to calculate with it
int totalResults = int.Parse( token );
}
}
Demo
Consider the this is in Mytext of string type variable
now
Mytext.Substring(Mytext.indexof("totalResults="),7);
//the function indexof will return the point wheres the value start,
//and 7 is a length of charactors that you want to extract
I am using similar of this ........
You can read with Linq2Xml, numResults and totalResults are Attributes, and <colors numResults="100" totalResults="6806926"> is Element, so you can simply get it by nmyXmlElement.Attributes("totalResults").
This function will split the string into a list of key value pairs which you can then pull out whatever you require
static List<KeyValuePair<string, string>> getItems(string s)
{
var retVal = new List<KeyValuePair<String, string>>();
var items = s.Split(' ');
foreach (var item in items.Where(x => x.Contains("=")))
{
retVal.Add(new KeyValuePair<string, string>( item.Split('=')[0], item.Split('=')[1].Replace("\"", "") ));
}
return retVal;
}
You can use regular expressions:
string input = "colors numResults=\"100\" totalResults=\"6806926\"";
string pattern = "totalResults=\"(?<results>\\d+?)\"";
Match result = new Regex(pattern).Match(input);
Console.WriteLine(result.Groups["results"]);
Be sure to have this included:
using System.Text.RegularExpressions;

Convert array of strings to Dictionary<string, int> c# then output to Visual Studio

I have an array of strings like so:
[0]Board1
[1]Messages Transmitted75877814
[2]ISR Count682900312
[3]Bus Errors0
[4]Data Errors0
[5]Receive Timeouts0
[6]TX Q Overflows0
[7]No Handler Failures0
[8]Driver Failures0
[9]Spurious ISRs0
just to clarify the numbers in the square brackets indicate the strings position in the array
I want to convert the array of strings to a dictionary with the string to the left of each number acting as the key, for example (ISR Count, 682900312)
I then want to output specific entries in the dictionary to a text box/table in visual studio (which ever is better) it would be preferable for the numbers to be left aligned.
excuse my naivety, I'm a newbie!
Pretty Simple. Tried and Tested
string[] arr = new string[] { "Board1", "ISR Count682900312", ... };
var numAlpha = new Regex("(?<Alpha>[a-zA-Z ]*)(?<Numeric>[0-9]*)");
var res = arr.ToDictionary(x => numAlpha.Match(x).Groups["Alpha"],
x => numAlpha.Match(x).Groups["Numeric"]);
string[] strings =
{
"Board1", "Messages232"
};
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach (var s in strings)
{
int index = 0;
for (int i = 0; i < s.Length; i++)
{
if (Char.IsDigit(s[i]))
{
index = i;
break;
}
}
dictionary.Add(s.Substring(0, index), int.Parse(s.Substring(index)));
}
var stringArray = new[]
{
"[0]Board1",
"[1]Messages Transmitted75877814",
"[2]ISR Count682900312",
"[3]Bus Errors0",
"[4]Data Errors0",
"[5]Receive Timeouts0",
"[6]TX Q Overflows0",
"[7]No Handler Failures0",
"[8]Driver Failures0",
"[9]Spurious ISRs0"
};
var resultDict = stringArray.Select(s => s.Substring(3))
.ToDictionary(s =>
{
int i = s.IndexOfAny("0123456789".ToCharArray());
return s.Substring(0, i);
},
s =>
{
int i = s.IndexOfAny("0123456789".ToCharArray());
return int.Parse(s.Substring(i));
});
EDIT: If the numbers in brackets are not included in the strings, remove .Select(s => s.Substring(3)).
Here you go:
string[] strA = new string[10]
{
"Board1",
"Messages Transmitted75877814",
"ISR Count682900312",
"Bus Errors0",
"Data Errors0",
"Receive Timeouts0",
"TX Q Overflows0",
"No Handler Failures0",
"Driver Failures0",
"Spurious ISRs0"
};
Dictionary<string, int> list = new Dictionary<string, int>();
foreach (var item in strA)
{
// this Regex matches any digit one or more times so it picks
// up all of the digits on the end of the string
var match = Regex.Match(item, #"\d+");
// this code will substring out the first part and parse the second as an int
list.Add(item.Substring(0, match.Index), int.Parse(match.Value));
}

Categories