String list G is :
[0] : {"1,2,5"}
[1] : {"1,2,4,5,6"}
[2] : {"2,4,6"}
[3] : {"1,4,6"}
With the following commands, we conclude that "1,4" exists in the List G[3] :
if (G[i].Contains("1,4")) { //code here }
How to modify the above commands, that in addition feature (Contains), "1,4" exists in the List G[1]?
Program codes
for (int i = 0; i < candid.Count; i++)
{
foreach (TransactionTP b in transactions)
{
string search = candid[i];
var searchNumbers = search.Split(',').Select(int.Parse).ToList();
for (int j = 0; j < G.Count; j++)
{
IEnumerable<int> numbers = G[j].Split(',').Select(int.Parse);
int idx = 0;
foreach (var number in numbers)
{
if (number == searchNumbers[idx])
{
idx++;
}
if (idx == searchNumbers.Count)
{
arraye[i] = arraye[i] + (b.transactionUtility);
break;
}
}
}
}
}
Update:
The order of the searched term matters.
In order to preserve the ordering of the set you are matching go (4,1 in this case), you will need to evaluate each string, keeping track of where you are in the match.
string[] G = new[]
{
"1,2,5",
"1,2,4,5,6",
"2,4,6",
"1,4,6"
};
string search = "1,4";
var searchNumbers = search.Split(',').Select(int.Parse).ToList();
for (int i = 0; i < G.Length; i++)
{
// Convert the string into an enumeration of numbers
IEnumerable<int> numbers = G[i].Split(',').Select(int.Parse);
// Index to keep track of the search
int idx = 0;
// Loop through the input set sequentially
foreach (var number in numbers)
{
// Check if the input matches the next expected number
if (number == searchNumbers[idx])
{
idx++;
}
if (idx == searchNumbers.Count)
{
Console.WriteLine("String {0} matched", G[i]);
break;
}
}
}
Replace your single Contains call with a method that does this:
bool passes = false;
for(int i = 0; i < G.Length; i++)
{
List<string> temp = new List<string>();
if(G[i].Contains(","))
{
temp = G[i].Split(",");
}
else
{
temp = G[i];
}
if(temp.Contains("1") && temp.Contains("4")
{
passes = true;
}
}
return passes;
This eliminates the possibility of matching on "10" or "41" etc etc
It also will not care if your elements are sorted, even though you said they are. It will also match regardless of the number of entries between "1" and "4" in the list.
You could spice this up to take any number of inputs that you want to match before qualifying as a match, I'll leave that to you if you want to make it so.
Related
I am wondering if strings have functionality that can see if a string contains words or words and other types of characters in general. (ideally I want to only consider strings that have readable sentences but that may too advanced) I am trying to count strings in a list that have that kind of text. I do not want to add to the count any strings that are only numbers, blank spaces, tabs or symbols (like ?, #, #) or even random letters unless there is at least some words contained in the string.
The strings will be initialised with "" so the code in the if statement - (this.ElementAt(i).getNotarised().ElementAt(j).getError() != "") - would be fine if there was no input at all. Unfortunately I am expecting some input in some case so this case also counts scenarios where there are only spaces, number, symbols or all of the 3 - which I do not want.
this is referring to a class inheriting from List
.getNotarised() returns a List
/** Find the highest/lowest amount of errors/solutions/suggestions/comments.
* If it's ASC then return the lowest to highest.
* If it's DESC then return the highest to lowest.
* Return a list with LOGS in the correct order.
* */
public List<LOG> highORlow(string asc_desc, string category)
{
int count = 0;
int[] array = new int[this.Count()];
for(int i = 0; i <= this.Count()-1; i++)
{
for(int j = 0; j <= this.ElementAt(i).getNotarised().Count()-1; j++)
{
if(this.ElementAt(i).getNotarised().ElementAt(j).getError() != "")
{
++count;
}
}
array[i] = count;
}
return new List<LOG>();
}
Point of interest:
string pattern = "[A-Za-z]{5}[0-9]{0}";
Regex xp = new Regex(pattern);
Use xp.IsMatch() to check if the pattern is matched.
/** Find the highest/lowest amount of errors/solutions/suggestions/comments.
* If it's true (ASC) then return the lowest to highest.
* If it's false (DESC) then return the highest to lowest.
* Return a list with LOGS in the correct order.
* */
public List<LOG> highORlow(bool asc_desc, string category)
{
int count = 0;
string pattern = "[A-Za-z]{5}[0-9]{0}";
Regex xp = new Regex(pattern);
Dictionary<LOG, int> array = new Dictionary<LOG, int>();
for (int i = 0; i <= this.Count() - 1; i++)
{
for (int j = 0; j <= this.ElementAt(i).getNotarised().Count() - 1; j++)
{
if (category == "ERROR")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getError()))
{
++count;
continue;
}
}
if (category == "SOLUTION")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getSolution()))
{
++count;
continue;
}
}
if (category == "SUGGESTION")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getSuggestion()))
{
++count;
continue;
}
}
if (category == "COMMENT")
{
if (xp.IsMatch(this.ElementAt(i).getNotarised().ElementAt(j).getComment()))
{
++count;
continue;
}
}
}
array.Add(this.ElementAt(i), count);
count = 0;
}
List<LOG> list = new List<LOG>();
if(asc_desc)
{
foreach (KeyValuePair<LOG, int> v in array.OrderBy(key => key.Value))
{
list.Add(v.Key);
}
}
else
{
foreach (KeyValuePair<LOG, int> v in array.OrderByDescending(key => key.Value))
{
list.Add(v.Key);
}
}
return list;
}```
Okay, I know that this code is crude, and all around a messy, but I am no programmer, so bear with me. I have this code that lists a bunch of numbers, but I want it to not list any circular copies of the numbers.
For example, if the number 111262 is on my list, I don't want 112621, 126211, 262111, 621112, or 211126 to be listed.
Sorry, that number cannot be on the list.
For a true example, if the number 111252 is on my list, I don't want 112521, 125211, 252111, 521112, or 211125 to be listed.
Any help is appreciated!
namespace Toric_Classes
{
class Program
{
static void Main(string[] args)
{
int number_of_perms=0;
bool badsubsum1;
bool badsubsum2;
int subsum1 = 0;
int subsum2 = 0;
int sum = 0;
int class_length=6;
int[] toric_class=new int[class_length];
// The nested for loops scroll through every possible number of length class_length, where each digit can have a value of 1,2,..., or class_length-1
// Each number is looked at as an array, and is not stored anywhere, only printed if it satisfies certain conditions
for(int i1=1; i1<class_length; i1++)
{
toric_class[0] = i1;
for (int i2 = 1; i2 < class_length; i2++)
{
toric_class[1] = i2;
for (int i3 = 1; i3 < class_length; i3++)
{
toric_class[2] = i3;
for (int i4 = 1; i4 < class_length; i4++)
{
toric_class[3] = i4;
for (int i5 = 1; i5 < class_length; i5++)
{
toric_class[4] = i5;
for (int i6 = 1; i6 < class_length; i6++)
{
badsubsum1 = false;
badsubsum2 = false;
toric_class[5] = i6;
// Find the value of the sum of the digits of our array.
// We only want numbers that have a total digit sum being a multiple of class_length
for (int k = 0; k < class_length; k++)
{
sum += toric_class[k];
}
// The follwong two nested loops find the value of every contiguous subsum of our number, but not the total subsum.
// We *do not* want any subsum to be a multiple of class_length.
// That is, if our number is, say, 121342, we want to find 1+2, 1+2+1, 1+2+1+3, 1+2+1+3+4, 2+1, 2+1+3, 2+1+3+4, 2+1+3+4+2, 1+3, 1+3+4, 1+3+4+2, 3+4, 3+4+2, and 4+2
// The following checks 1+2, 1+2+1, 1+2+1+3, 1+2+1+3+4, 2+1, 2+1+3, 2+1+3+4, 1+3, 1+3+4, and 3+4
for (int i = 0; i < class_length - 1; i++)
{
for (int j = i + 1; j < class_length - 1; j++)
{
for (int k = i; k < j; k++)
{
subsum1 += toric_class[k];
}
if (subsum1 % class_length == 0)
{
badsubsum1 = true;
break;
}
subsum1 = 0;
}
}
// The following checks 2+1, 2+1+3, 2+1+3+4, 2+1+3+4+2, 1+3, 1+3+4, 1+3+4+2, 3+4, 3+4+2, and 4+2
for (int i = 1; i < class_length; i++)
{
for (int j = i + 1; j < class_length; j++)
{
for (int k = i; k < j; k++)
{
subsum2 += toric_class[k];
}
if (subsum2 % class_length == 0)
{
badsubsum2 = true;
break;
}
subsum2 = 0;
}
}
// We only want numbers that satisfies the following conditions
if (sum % class_length == 0 && badsubsum1 == false && badsubsum2 == false)
{
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
number_of_perms++;
}
sum = 0;
subsum1 = 0;
subsum2 = 0;
}
}
}
}
}
}
Console.WriteLine("Number of Permuatations: "+number_of_perms);
Console.Read();
}
}
}
EDIT
To clarify, I am creating a list of all numbers with length n that satisfy certain conditions. Consider the number d1d2...dn, where each di is a digit of our number. Each di may have value 1,2,...,n. Our number is in the list if it satisfies the following
The sum of all the digits is a multiple of n, that is,
d1+d2+...+dn = 0 mod n
Every contiguous subsum of the digits is not a multiple of n, aside from the total sum, that is, if i !=1 and j != n, then
di+d(i+1)+...+dj != 0 mod n
I should mention again that a "number" does not strictly use the numbers 0-9 in its digits. It may take any value between 1 and n. In my code, I am using the case where n=6.
The code works by creating an array of length class_length (in the code above, I use class_length=6). We first have 6 nested for loops that simply assign values to the array toric_class. The first for assigns toric_class[0], the second for assigns toric_class[1], and so on. In the first go around, we are generating the array 111111, then 111112, up to 111115, then 111121, etc. So essentially, we are looking at all heximal numbers that do not include 0. Once we reach our sixth value in our array, we check the array toric_class and check its values to ensure that it satisfies the above conditions. If it does, we simply print the array in a line, and move on.
Here is my easy and inefficient way that should work with minimal changes to your code. It requires shared string list var strList = new List<string>(); to store the used numbers. Then this part:
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
number_of_perms++;
becomes something like this:
string strItem = " " + string.Join(" ", toric_class) + " "; // Example: int[] {1, 12, 123} becomes " 1 12 123 "
if (!strList.Any(str => str.Contains(strItem))) // Example: if " 1 12 123 1 12 123 " contains " 1 12 123 "
{
Console.WriteLine(strItem);
strItem += strItem.Substring(1); // double the string, but keep only one space between them
strList.Add(strItem);
}
number_of_perms++; // not sure if this should be in the if statement
The idea is that for example the string " 1 1 1 2 5 2 1 1 1 2 5 2 " contains all circular copies of the numbers {1, 1, 1, 2, 5, 2}. I used string as a lazy way to check if array contains sub-array, but you can use similar approach to store copy of the used numbers in a list of arrays new List<int[]>() and check if any of the arrays in the list is circular copy of the current array, or even better HashSet<int[]>() approach similar to #slavanap's answer.
The first version of my answer was the easiest, but it works only with array of single digit items.
List is almost the same as array (new List<string>() instead of new string[]), but makes it much easier and efficient to add items to it. For example {1,2}.Add(3) becomes {1,2,3}.
str => str.Contains(strItem) is shortcut for a function that accepts parameter str and returns the result of str.Contains(strItem). That "function" is then passed to the .Any LINQ extension, so
strList.Any(str => str.Contains(strItem))
is shortcut for something like this:
foreach(string str in strList)
{
if (str.Contains(strItem))
{
return true;
}
}
return false;
The following method:
private static List<int> GetCircularEquivalents(int value)
{
var circularList = new List<int>();
var valueString = value.ToString();
var length = valueString.Length - 1;
for (var i = 0; i < length; i++)
{
valueString = valueString.Substring(1, length) + valueString.Substring(0, 1);
circularList.Add(int.Parse(valueString));
}
return circularList;
}
will return a list of the circular numbers derived from the input value. Using your example, this method can be called like this:
var circularList = GetCircularEquivalents(111262);
var dirtyList = new List<int> { 1, 112621, 2, 126211, 3, 262111, 4, 621112, 5, 211126, 6 };
var cleanList = dirtyList.Except(circularList).ToList();
which would result in a cleanList made up of the numbers 1 through 6, i.e. the dirtyList with all the circular numbers derived from 111262 removed.
That's where OOP really benefits. Comments inlined.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3 {
struct MyInt : IEquatable<MyInt> {
private int _value;
public MyInt(int value) {
_value = value;
}
// make it look like int
static public implicit operator MyInt(int value) {
return new MyInt(value);
}
public static explicit operator int(MyInt instance) {
return instance._value;
}
// main difference in these 3 methods
private int GetDigitsNum() {
int temp, res;
for (res = 0, temp = Math.Abs(_value); temp > 0; ++res, temp /= 10);
return res;
}
public bool Equals(MyInt other) {
int digits = other.GetDigitsNum();
if (digits != this.GetDigitsNum())
return false;
int temp = other._value;
// prepare mul used in shifts
int mul = 1;
for (int i = 0; i < digits - 1; ++i)
mul *= 10;
// compare
for (int i = 0; i < digits; ++i) {
if (temp == _value)
return true;
// ROR
int t = temp % 10;
temp = temp / 10 + t * mul;
}
return false;
}
public override int GetHashCode() {
// hash code must be equal for "equal" items,
// that's why use a sum of digits.
int sum = 0;
for (int temp = _value; temp > 0; temp /= 10)
sum += temp % 10;
return sum;
}
// be consistent
public override bool Equals(object obj) {
return (obj is MyInt) ? Equals((MyInt)obj) : false;
}
public override string ToString() {
return _value.ToString();
}
}
class Program {
static void Main(string[] args) {
List<MyInt> list = new List<MyInt> { 112621, 126211, 262111, 621112, 211126 };
// make a set of unique items from list
HashSet<MyInt> set = new HashSet<MyInt>(list);
// print that set
foreach(int item in set)
Console.WriteLine(item);
}
}
}
Output:
112621
I've written a code that has a list and I want to sort the list alphabetically and numerically.
For example the first items in the list are
list[0] = "INPUT 10"
list[1] = "INPUT 5".
I want my list reorganized like this:
list[0] = "INPUT 5"
list[1] = "INPUT 10".
So basically my program gets checked items from a checked list box,stores them in a list, and I want it to reorganize the list alphabettically.
The checked list box has items like INPUT 1,INPUT 2,INPUT 3...and so fourth. Can anyone suggest me a way of how to go about this?
UPDATED CODE
I've updated my code and now this code splits the strings into INPUT and 10.The "q" list obtains the checked items in the input box,the string "s" array gets the splittd data from the q list. Then the "numbers" list gets only the number part of the string for example "INPUT 5",the number list will only get "5".Then I want to sort these numbers and build another string combining the sorted number list and the string "INPUT" and add it to the output checkedlistbox. My code isnt working though...any suggestions?It should sort the numbers but it doesnt...anyone have any suggestions of why this code isnt working? And I keep on getting error messages of the array being able to unhandle negative integers and what not.
List<string> q = new List<string>();
List<string> numbers = new List<string>();
private void button_ekle_Click(object sender, EventArgs e)
{
for (int k = clb_input.Items.Count - 1; k >= 0; k--)
{
if (clb_input.GetItemChecked(k) == true)
{
q.Add(clb_input.Items[k].ToString());
//clb_output.Items.Add(clb_input.Items[k]);
clb_input.Items.RemoveAt(k);
}
else { }
}
string[] s = new string[q.Count * 2];
//string[] numbers=new string[q.Count/2];
for (int t = 1; t <= q.Count * 2; t++)
{
if (q != null)
s = q[t - 1].ToString().Split(' ');
else { s[t] = null; }
}
for (int x = 1; x <= q.Count; x++)
{
if (s[2 * x - 1] != null)
{
numbers[x - 1] = s[2 * x - 1];
numbers.Sort();
clb_output.Items.Add("INPUT "+ numbers[x - 1].ToString());
}
else { numbers[x - 1] = null; }
}
}
What you need is Alphanumeric Sorting ( most commonly seen in windows explorer, the way files are sorted)
Code can be found here : http://www.dotnetperls.com/alphanumeric-sorting
Sample
class Program
{
static void Main()
{
string[] highways = new string[]
{
"100F",
"50F",
"SR100",
"SR9"
};
//
// We want to sort a string array called highways in an
// alphanumeric way. Call the static Array.Sort method.
//
Array.Sort(highways, new AlphanumComparatorFast());
//
// Display the results
//
foreach (string h in highways)
{
Console.WriteLine(h);
}
}
}
Output
50F
100F
SR9
SR100
Implementation
public class AlphanumComparatorFast : IComparer
{
public int Compare(object x, object y)
{
string s1 = x as string;
if (s1 == null)
{
return 0;
}
string s2 = y as string;
if (s2 == null)
{
return 0;
}
int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;
// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
char ch1 = s1[marker1];
char ch2 = s2[marker2];
// Some buffers we can build up characters in for each chunk.
char[] space1 = new char[len1];
int loc1 = 0;
char[] space2 = new char[len2];
int loc2 = 0;
// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;
if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));
do
{
space2[loc2++] = ch2;
marker2++;
if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(space1);
string str2 = new string(space2);
int result;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}
if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}
The simplest solution is to just left-pad the numerical values with a space to the same length.
List<string> lst = new List<string>
{
"Item 9",
"Item 999",
"Thing 999",
"Thing 5",
"Thing 1",
"Item 20",
"Item 10",
};
lst.Sort();
Output:
Item 9
Item 10
Item 20
Item 999
Thing 1
Thing 5
Thing 999
And you can always remove the extra white space used for padding after the sorting operation is performed.
You can use Sort with a Comparer like this:
List<string> q = new List<string>();
private void button_ekle_Click(object sender, EventArgs e)
{
for (int k=clb_input.Items.Count-1; k >= 0; k--)
{
if (clb_input.GetItemChecked(k) == true)
{
q.Add(clb_input.Items[k].ToString());
clb_input.Items.RemoveAt(k);
}
else { }
}
q.Sort((p1,p2)=>((int)(p1.split(" ")[1])).CompareTo((int)(p2.split(" ")[1])));
for (int t = 0; t < q.Count; t++)
{
clb_output.Items.Add(q[t].ToString());
}
}
I've got a booking service in which you can select by an enum if you want to display all seats, all available seats or all booked seats.
My problem is that I don't know how to make it so i.e. only the booked seats are shown, because as of now if I select "only booked seats" it shows the correct number of reserved seats, but it iterates from the beginning of the entire array instead of the ones that I want, so if there are 3 reserved seats, it will show seat 0,1,2 instead of the ones that are actually reserved.
I am pretty sure that I need to change the for (int i = 0; i < count; i++) to for (int i = 0; i < totalNumberOfSeats; i++) instead to actually loop through all seats instead of just as many as there are of the kind that I want to display, but then I get out of bound exception and I don't know how to proceed.
public string[] GetSeatInfoStrings(DisplayOptions choice)
{
int count = GetNumOfSeats(choice);
if (count <= 0)
{
return null;
}
string[] strSeatInfoStrings = new string[count];
for (int i = 0; i < count; i++)
{
strSeatInfoStrings[i] = GetSeatInfoAt(i);
}
return strSeatInfoStrings;
}
public string GetSeatInfoAt(int index)
{
int row = GetRow(index);
int col = GetCol(index);
string seatInfo;
if (string.IsNullOrEmpty(GetName(m_nameMatrix[row, col])))
{
seatInfo = MarkAsVacant(row, col);
}
else
{
seatInfo = MarkAsReserved(row, col);
}
return seatInfo;
}
I've got a method IsReserved(int index) and tried something like this
if (IsReserved(i))
{
// Want to return all seats that are reserved
}
else if (!IsReserved(i))
{
// Want to return all seats that are NOT reserved
}
As far as for that method working, it is okay, but the problem is that I don't know what to put within the brackets.
This is a question where we cant help without knowing your complete model. There is little detail. May be you want something like this:
string[] strSeatInfoStrings = new string[count];
int counter = 0;
for (int i = 0; i < totalNumberOfSeats; i++)
{
var seatInfo = GetSeatInfoAt(i);
if (seatInfo == "reserved") //some kind of checking
{
strSeatInfoStrings[counter] = seatInfo;
counter++; //run another counter
}
}
return strSeatInfoStrings;
You can avoid all the hassle of array and counter and just use a List<T>..
var strSeatInfoStrings = new List<string>();
for (int i = 0; i < totalNumberOfSeats; i++)
{
var seatInfo = GetSeatInfoAt(i);
if (seatInfo == "reserved") //some kind of checking
strSeatInfoStrings.Add(seatInfo);
}
return strSeatInfoStrings;
It's probably easier to use a List than an array in this case, because with a List you don't need to know the size before you start adding to it.
public string[] GetSeatInfoStrings(DisplayOptions choice)
{
List<string> lstSeatInfoStrings = new List<string>();
for (int i = 0; i < totalNumberOfSeats; i++)
{
string seatInfo = GetSeatInfoAt(i);
if (seatInfo.Reserved)
{
lstSeatInfoStrings.Add(seatInfo);
}
}
if (lstSeatInfoStrings.Count == 0)
{
return null;
}
return lstSeatInfoStrings.ToArray();
}
I have many strings. Each string is prepended with at least 1 $. What is the best way to loop through the chars of each string to count how many $'s there are per string.
eg:
"$hello" - 1
"$$hello" - 2
"$$h$ello" - 2
You could use the Count method
var count = mystring.Count(x => x == '$')
int count = myString.TakeWhile(c => c == '$').Count();
And without LINQ
int count = 0;
while(count < myString.Length && myString[count] == '$') count++;
The simplest approach would be to use LINQ:
var count = text.TakeWhile(c => c == '$').Count();
There are certainly more efficient approaches, but that's probably the simplest.
You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while loop and check every character), but it works.
int count = test.Split('$').Length - 1;
var str ="hello";
str.Where(c => c == 'l').Count() // 2
int count = yourText.Length - yourText.TrimStart('$').Length;
int count = Regex.Matches(myString,"$").Count;
public static int GetHowManyTimeOccurenceCharInString(string text, char c)
{
int count = 0;
foreach(char ch in text)
{
if(ch.Equals(c))
{
count++;
}
}
return count;
}
just a simple answer:
public static int CountChars(string myString, char myChar)
{
int count = 0;
for (int i = 0; i < myString.Length; i++)
{
if (myString[i] == myChar) ++count;
}
return count;
}
Cheers! - Rick
One approach you could take is the following method:
// Counts how many of a certain character occurs in the given string
public static int CharCountInString(char chr, string str)
{
return str.Split(chr).Length-1;
}
As per the parameters this method returns the count of a specific character within a specific string.
This method works by splitting the string into an array by the specified character and then returning the length of that array -1.
//This code worked for me
class CountOfLettersOfString
{
static void Main()
{
Console.WriteLine("Enter string to check count of letters");
string name = Console.ReadLine();
//Method1
char[] testedalphabets = new char[26];
int[] letterCount = new int[26];
int countTestesd = 0;
Console.WriteLine($"Given String is:{name}");
for (int i = 0; i < name.Length - 1; i++)
{
int countChar = 1;
bool isCharTested = false;
for (int j = 0; j < testedalphabets.Length - 1; j++)
{
if (name[i] == testedalphabets[j])
{
isCharTested = true;
break;
}
}
if (!isCharTested)
{
testedalphabets[countTestesd] = name[i];
for (int k = i + 1; k < name.Length - 1; k++)
{
if (name[i] == name[k])
{
countChar++;
}
}
letterCount[countTestesd] = countChar;
countTestesd++;
}
else
{
continue;
}
}
for (int i = 0; i < testedalphabets.Length - 1; i++)
{
if (!char.IsLetter(testedalphabets[i]))
{
continue;
}
Console.WriteLine($"{testedalphabets[i]}-{letterCount[i]}");
}
//Method2
var g = from c in name.ToLower().ToCharArray() // make sure that L and l are the same eg
group c by c into m
select new { Key = m.Key, Count = m.Count() };
foreach (var item in g)
{
Console.WriteLine(string.Format("Character:{0} Appears {1} times", item.Key.ToString(), item.Count));
}
Console.ReadLine();
}
}
This is a similar Solution to find how many email addresses included in a string. This way is more efficient`
int count = 0;
foreach (char c in email.Trim())
if (c == '#') count++;