'if' character count or different values - c#

Please excuse the rubbish title, I don't know how to word it properly. I am wondering how I can use this code:
int cnt = 0;
foreach (char c in test) {
if (c == '&') cnt++;
}
from this question and instead of adding 1 to the count for 'just' &, add 1 to the count for & or # or %?

You can directly count using .Count and with using Linq
var cnt = test.Count(c => c == '&' || c == '#' || c == '%');

It's easy, just add more conditions:
int cnt = 0;
foreach (char c in test) {
if (c == '&' || c == '#' || c == '%') cnt++;
}

You could use Regex:
cnt = Regex.Matches(test, "[&#%]").Count

string pattern = "&#%";
int cnt = 0;
foreach (char c in test)
{
if (pattern.IndexOf(c) != -1) cnt++;
}

Related

Split string at particular characters (C#)

What I want to do is to split an array and then put the character which i split at into another element
i.e. string text = "1*5+89-43&99" should become string[] textsplit = ["1","*","5","+","89","-","43","&","99"] (it must be a string)
and I will supply the characters to be left in seperate elements
You can do this using string.IndexOfAny.
Simply keep looking for the next index of any of the separators. When you find a separator, add the text between it and the last separator to your results, then look for the next separator.
string input = "1*1*5+89-43&33";
var separators = new[] { '+', '-', '*', '/', '&' };
var result = new List<string>();
int index;
int lastIndex = 0;
while ((index = input.IndexOfAny(separators, lastIndex)) != -1)
{
// Add the text before the separator, if there is any
if (index - lastIndex > 0)
{
result.Add(input.Substring(lastIndex, index - lastIndex));
}
// Add the separator itself
result.Add(input[index].ToString());
lastIndex = index + 1;
}
// Add any text after the last separator
if (lastIndex < input.Length)
{
result.Add(input.Substring(lastIndex));
}
Try with the following code snippet:
string text = "1*1*5+89-43&33";
List<string> textsplit = new List<string>();
foreach(var match in Regex.Matches(text, #"([*+/\-)(])|([0-9]+)"))
{
textsplit.Add(match.ToString());
}
Result added as an image.
Here's a basic and naive implementation that I beliewe will do what you want:
public static List<string> SplitExpression(string expression)
{
var parts = new List<string>();
bool isNumber(char c) => c == '.' || (c >= '0' && c <= '9');
bool isOperator(char c) => !isNumber(c);
int index = 0;
while (index < expression.Length)
{
char c = expression[index];
index++;
if (isNumber(c))
{
int numberIndex = index - 1;
while (index < expression.Length && isNumber(expression[index]))
index++;
parts.Add(expression.Substring(numberIndex, index - numberIndex));
}
else
parts.Add(c.ToString());
}
// move unary signs into following number
index = 0;
while (index < parts.Count - 1)
{
bool isSign = parts[index] == "-" || parts[index] == "+";
bool isFirstOrFollowingOperator = index == 0 || isOperator(parts[index - 1][0]);
bool isPriorToNumber = isNumber(parts[index + 1][0]);
if (isSign && isFirstOrFollowingOperator && isPriorToNumber)
{
parts[index + 1] = parts[index] + parts[index + 1];
parts.RemoveAt(index);
}
else
index++;
}
return parts;
}
Example input: "-1+-2*-10.1*.1", and output:
-1
+
-2
*
-10.1
*
.1

How to make an incremental dynamic code that contains alphabets and numerics

My initial code is 'A0AA' and I need a code/function in C# that will increment it until it goes to 'Z9ZZ'.
for example.
first code is 'D9ZZ'
the next code should be 'E0AA'
sorry maybe my example is quite confusing.. here's another example.. thanks.
first code is 'D9AZ'
the next code should be 'D9BA'
string start = "A9ZZ";
int add = 1;
string next = String.Concat(start.Reverse().Select((x,i) =>
{
char first = i == 2 ? '0' : 'A';
char last = i == 2 ? '9' : 'Z';
if ((x += (char)add) > last)
{
return first;
}
else
{
add = 0;
return x;
}
})
.Reverse());
This should fix it.
private static IEnumerable<string> Increment(string value)
{
if (value.Length != 4)
throw new ArgumentException();
char[] next = value.ToCharArray();
while (new string(next) != "Z9ZZ")
{
next[3]++;
if (next[3] > 'Z')
{
next[3] = 'A';
next[2]++;
}
if (next[2] > 'Z')
{
next[2] = 'A';
next[1]++;
}
if (next[1] > '9')
{
next[1] = '0';
next[0]++;
}
yield return new string(next);
}
}
Example of calling this code:
IList<string> values = Increment("A0AA").Take(100).ToList();
foreach (var value in values)
{
Console.Write(value + " ");
}
Here's a pretty clean solution that checks every character starting at the end:
public SomeMethod()
{
var next = Increment("A2CZ"); // A2DZ
}
public string Increment(string code)
{
var arr = code.ToCharArray();
for (var i = arr.Length - 1; i >= 0; i--)
{
var c = arr[i];
if (c == 90 || c == 57)
continue;
arr[i]++;
return new string(arr);
}
return code;
}

c# finding characters between brackets

I can't get it to work,
I need to get a character ex : i [L]ove [B]asketball and [H]ockey
i would like to take the L, B and H out of this string and show them in a console writeline
without using regex
I though about finding the position of [ with an indexof and add + 1 to get the letter and then replace the [ with something else ex: [ into &
so i could do a foreach bracket in that string... but i don't think it'll work o.O
Console.WriteLine("Characters are : ");
foreach(Brackets in sentence)..
string str = " i [L]ove [B]asketball and [H]ockey";
string[] array = str.Split('[');
foreach (var item in array)
{
if(item.Contains(']'))
Console.WriteLine(item[0]);
}
and you will get:
L
B
H
This would work as long as you don't have unpaired square brackets and there is a character between those square brackets.
You can do this without the split:
string str = " i [L]ove [B]asketball and [H]ockey";
for (int i = 0; i < str.Length; i++)
{
if(str[i] == '[')
Console.WriteLine(str[1 + i++]);
}
Using LINQ:
string s = "i [L]ove [B]asketball and [H]ockey";
var chars = s.Where((c, i) => i > 0 && s[i - 1] == '[' &&
i < s.Length - 1 && s[i + 1] == ']');
Equivalently:
var chars = Enumerable.Range(1, s.Length - 2)
.Where(i => s[i - 1] == '[' && s[i + 1] == ']')
.Select(i => s[i]);
You can use this regex to get the values between the brakets:
string input = "I [L]ove [B]asketball and [H]ockey";
var regex = new Regex(#"\[.*?\]");
var matches = regex.Matches(input);
foreach (var match in matches)
{
var letter = Regex.Replace(match.ToString(), #"\[|\]", string.Empty);
Console.WriteLine(letter);
}
With regex:
string str = " i [L]ove [B]asketball and [H]ockey";
Match match = Regex.Match(str, #"\[(.*?)\]");
StringBuilder sb = new StringBuilder();
//iterate over all matches
do
{
sb.Append(match);
match = match.NextMatch();
}while(match.Success); //condition
//note: Dump() only works in linqpad. Use Console.WriteLine() instead
sb.Dump();
//without brackets:
sb.ToString().Split(new []{'[',']'}, StringSplitOptions.RemoveEmptyEntries).Dump();
I have come up with lengthy code but it works with all the cases
Try This:
static void Main()
{
string line = "i [L]ove [B]asketball and [H]ockey";
int count = 0;
char temp=' ';
string str="";
foreach (char ch in line)
{
if (ch == '[')
{
count++;
}
else if (count ==1)
{
count++;
temp=ch;
}
else if(count==2 && ch==']')
{
str+=temp;
count=0;
}
else
{
count = 0;
}
}
Console.WriteLine(str);
}

Delete all english letters in string

I need to delete all english letters in a string.
I wrote the following code:
StringBuilder str = new StringBuilder();
foreach(var letter in test)
{
if(letter >= 'a' && letter <= 'z')
continue;
str.Append(letter); }
What is the fastest way?
use Regex replace method, and give it [a-z]|[A-Z]
Try this:
var str = test.Where(item => item < 'A' || item > 'z' || (item > 'Z' && item < 'a'));
Use this method to do such execution....
public static string RemoveSpecialCharacters(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
continue;
else
sb.Append(c);
}
return sb.ToString();
}

How to make this function not prematurely split?

I've written this function...
internal static IEnumerable<KeyValuePair<char?, string>> SplitUnescaped(this string input, char[] separators)
{
int index = 0;
var state = new Stack<char>();
for (int i = 0; i < input.Length; ++i)
{
char c = input[i];
char s = state.Count > 0 ? state.Peek() : default(char);
if (state.Count > 0 && (s == '\\' || (s == '[' && c == ']') || ((s == '"' || s == '\'') && c == s)))
state.Pop();
else if (c == '\\' || c == '[' || c == '"' || c == '\'')
state.Push(c);
if (state.Count == 0 && separators.Contains(c))
{
yield return new KeyValuePair<char?, string>(c, input.Substring(index, i - index));
index = i + 1;
}
}
yield return new KeyValuePair<char?, string>(null, input.Substring(index));
}
Which splits a string on the given separators, as long as they aren't escaped, in quotes, or in brackets. Seems to work pretty well, but there's one problem with it.
There characters I want to split on include a space:
{ '>', '+', '~', ' ' };
So, given the string
a > b
I want it to split on > and ignore the spaces, but given
a b
I do want it to split on the space.
How can I fix the function?
You could continue to split based on and > and then remove the strings which are empty.
I think this does it...
internal static IEnumerable<KeyValuePair<char?, string>> SplitUnescaped(this string input, char[] separators)
{
int startIndex = 0;
var state = new Stack<char>();
input = input.Trim(separators);
for (int i = 0; i < input.Length; ++i)
{
char c = input[i];
char s = state.Count > 0 ? state.Peek() : default(char);
if (state.Count > 0 && (s == '\\' || (s == '[' && c == ']') || ((s == '"' || s == '\'') && c == s)))
state.Pop();
else if (c == '\\' || c == '[' || c == '"' || c == '\'')
state.Push(c);
else if (state.Count == 0 && separators.Contains(c))
{
int endIndex = i;
while (input[i] == ' ' && separators.Contains(input[i + 1])) { ++i; }
yield return new KeyValuePair<char?, string>(input[i], input.Substring(startIndex, endIndex - startIndex));
while (input[++i] == ' ') { }
startIndex = i;
}
}
yield return new KeyValuePair<char?, string>(null, input.Substring(startIndex));
}
I was trying to push the space onto the stack too before, and then doing some checks against that...but I think this is easier.

Categories

Resources