I am having an issue solving Bracket Checker .
i cant seem to solve the problem if user input this sequence of bracket then my program must print its not a right sequence
Input:
({}[)
Output:
Not a Right Sequence
My code is below
Stack s = new Stack();
Queue q = new Queue();
bool isok = true;
string FinalData = "0";
Console.WriteLine("Enter Brackets");
string data = Console.ReadLine();
for (int i = 0; i < data.Length; i++)
{
if (data.Substring(i, 1) == "{"
|| data.Substring(i, 1) == "["
|| data.Substring(i, 1) == "("
)
{
s.Push(data.Substring(i, 1));
}
else
{
q.Enqueue(data.Substring(i, 1));
}
}
while (s.Count > 0 && q.Count > 0)
{
FinalData = (String)s.Pop();
string value = (String)q.Dequeue();
if (FinalData == value)
{
isok = false;
break;
}
}
if (isok)
Console.WriteLine(data + " is a Right Sequence.");
else
Console.WriteLine(data + " is Not a Right Sequence.");
Console.ReadLine();
}
I'l give you a few hints and the basic idea:
you don't need the Queue, just a Stack<char>.
read the input, for each char:
if the char is an open brace, push it
if the char is a close brace, pop the stack and compare.
discard other chars
boolean isCorrect;
public boolean checkBraces(String braces)
{
Stack<Character>stack = new Stack<Character>();
int openBCount = 0;
int closeBCount = 0;
for(int c = 0; c<=braces.length()-1; c++)
{
//check for open braces push to stack
if(braces.charAt(c)=='{' || braces.charAt(c)=='[' ||braces.charAt(c)=='(')
{
stack.push(braces.charAt(c));
openBCount++;
} ////check for close braces. pop the open braces
//compare it to the closed braces using the the
//method ValidatePerBraces
//therefor checking for CORRECTNEES of how the braces //are closed
else if(braces.charAt(c)=='}' || braces.charAt(c)==']' || braces.charAt(c)==')')
{
closeBCount++;
if(!ValidatePerBraces(stack.pop(), braces.charAt(c)))
{
isCorrect = false; //return false in case where they dont match
return isCorrect;
}
}
//for braces to be complete, open and close braces
//should be even, if they are not even then it is
//for sure wrong at least for the specification.
if(c>=braces.length()-1)
{
if(openBCount != closeBCount)
{
isCorrect = false;
return isCorrect;
}
}
}
isCorrect = true; // true if they all match
return isCorrect;
}
// returns true if validated
public boolean ValidatePerBraces(char a, char b)
{
return a == '(' && b== ')' || a == '[' && b == ']' || a == '{' && b== '}' ;
}
public bool CheckBraces(string data)
{
Stack<char> stack = new Stack<char>();
foreach(char c in data){
switch(c){
case '(':
case '[':
case '{':
stack.Push(c);
break;
case ')':
case ']':
case '}':
if(!CheckMatch(stack.Pop(),c)){
return false;
}
break;
}
}
return true;
}
private bool CheckMatch(char a, char b){
return a=='(' && b==')' ||
a=='[' && b==']' ||
a=='{' && b=='}';
}
Thannks Guys I have Solved The Problem Using stack And Queue Both AT the Same time. Here's the code
Stack s = new Stack();
Queue q = new Queue();
bool isRight = true;
char OpeningBracket = ' ';
char closingBracket = ' ';
Console.WriteLine("Enter Brackets");
string data = Console.ReadLine();
char[] character = data.ToCharArray();
for (int i = 0; i < character.Length; i++)
{
if (character[i] == '(' || character[i] == '{' ||
character[i] == '[')
{
s.Push(character[i]);
}
else
q.Enqueue(character[i]);
}
if (s.Count == 0 || q.Count == 0)
isRight = false;
while (s.Count > 0 && q.Count > 0)
{
OpeningBracket = (char)s.Pop();
closingBracket = (char)q.Dequeue();
if ((OpeningBracket == '(' && closingBracket != ')')
|| (OpeningBracket == '[' && closingBracket != ']')
|| (OpeningBracket == '{' && closingBracket != '}')
)
{
isRight = false;
}
}
if (isRight)
Console.WriteLine(data + " is a Right Sequence.");
else
Console.WriteLine(data + " is Not Right Sequence.");
Console.ReadLine();
}
private static bool IsCorrectBracketSeq(string sequence)
{
var stack = new Stack<char>();
foreach (var sign in sequence)
{
if(sign == '(' || sign == '[' || sign == '{')
stack.Push(sign);
else if (sign == ')' || sign == ']' || sign == '}')
{
if (!stack.Any())
return false;
var topSing = stack.Pop();
var str = $"{topSing}{sign}";
if (str != "[]" && str != "{}" && str != "()")
return false;
}
}
return stack.Count == 0;
}
static bool IsBracesValidator(string input)
{
bool IsValidBraces = true;
char[] chrArray = input.ToCharArray();
List<Char> foundOpenParanthesis = new List<char>();
List<Char> foundClosedParanthesis = new List<char>();
char[] chrOpenParanthesis = { '{', '[', '(', '<' };
char[] chrClosedParanthesis = { '}', ']', ')', '>' };
for (int i = 0; i <= chrArray.Length - 1; i++)
{
if (chrOpenParanthesis.Contains(chrArray[i]))
{
foundOpenParanthesis.Add(chrArray[i]);
}
if (chrClosedParanthesis.Contains(chrArray[i]))
{
foundClosedParanthesis.Add(chrArray[i]);
}
}
if (foundOpenParanthesis.Count == foundClosedParanthesis.Count)
{
for(int i=0;i< foundOpenParanthesis.Count;i++)
{
char chr = foundOpenParanthesis[i];
switch (chr)
{
case '[': chr = ']'; break;
case '<': chr = '>'; break;
case '(': chr = ')'; break;
case '{': chr = '}'; break;
}
if (!chr.Equals(foundClosedParanthesis[foundClosedParanthesis.Count - i-1]))
{
IsValidBraces = false;
break;
}
}
} else
{
IsValidBraces = false;
}
return IsValidBraces;
}
Related
I already found different solutions on Stackoverflow, but there were some things I didn´t understand.
Whats the best method to calculate the Output of e.g.: ((1+(4*(2+3)))+((2+3)*(4*5))) ?
My method looks as following, but I know there are lots of mistakes in it:
public static int ComputeInfix(string infix) {
Stack<char> operatorstack = new Stack<char>();
Stack<int> operandstack = new Stack<int>();
for(int j = 0; j < infix.Length; j++) {
char c = infix[j];
if (c => 0 && c <= 9) {
operandstack.Push(c);
}
else if ((c == '+' || c == '*' || c == '/' || c == '-')) {
if (operatorstack.IsEmpty()) {
operatorstack.Push(c);
}
else {
if (operatorstack.Peek() != '*' || operatorstack.Peek() != '/') {
operatorstack.Push(c);
}
}
}
else if (c == '(') {
operatorstack.Push(c);
}
else if (c == ')') {
operatorstack.Pop();
}
}
return infix;
}
Now changed it to:
Stack<char> operatorstack = new Stack<char>();
Stack<char> operandstack = new Stack<char>();
for(int j = 0; j < infix.Length; j++) {
char c = infix[j];
if (c => '0' && c <= '9') {
operandstack.Push(c);
}
But get error:
Infix.cs(16,8): error CS0136: A local variable named c' cannot be
declared in this scope because it would give a different meaning to
c', which is already used in a `parent or current' scope to denote
something else
Since I spent the time to write it, here is my solution:
public static int ComputeInfix(string infix) {
var operatorstack = new Stack<char>();
var operandstack = new Stack<int>();
var precedence = new Dictionary<char, int> { { '(', 0 }, { '*', 1 }, { '/', 1 }, { '+', 2 }, { '-', 2 }, { ')', 3 } };
foreach (var ch in $"({infix})") {
switch (ch) {
case var digit when Char.IsDigit(digit):
operandstack.Push(Convert.ToInt32(digit.ToString()));
break;
case var op when precedence.ContainsKey(op):
var keepLooping = true;
while (keepLooping && operatorstack.Count > 0 && precedence[ch] > precedence[operatorstack.Peek()]) {
switch (operatorstack.Peek()) {
case '+':
operandstack.Push(operandstack.Pop() + operandstack.Pop());
break;
case '-':
operandstack.Push(-operandstack.Pop() + operandstack.Pop());
break;
case '*':
operandstack.Push(operandstack.Pop() * operandstack.Pop());
break;
case '/':
var divisor = operandstack.Pop();
operandstack.Push(operandstack.Pop() / divisor);
break;
case '(':
keepLooping = false;
break;
}
if (keepLooping)
operatorstack.Pop();
}
if (ch == ')')
operatorstack.Pop();
else
operatorstack.Push(ch);
break;
default:
throw new ArgumentException();
}
}
if (operatorstack.Count > 0 || operandstack.Count > 1)
throw new ArgumentException();
return operandstack.Pop();
}
I want to remove parentheses only when the whole text is surrounded by them. For example:
(text (text) text)
need's to be convert to:
text (text) text
I have a very simple check:
value = (value [0] == '(' && value [value .Length - 1] == ')') ? value.Substring(1, value .Length - 2) : value;
but it fails and incorrectly removes the parentheses of these kind of strings:
(text (text) ) text (text)
Could anyone tell a way to handle all cases? Using regular expression is OK as well.
Note, that the parentheses are balanced. For example, such case is not possible:
( text ( text )
Use a simple loop for testing, if it's "valid" for removal, remove first & last:
bool isValid = value[0] == '(' && value[value.Length - 1] == ')';
int i = 1;
int c = 0;
for(; isValid && c >= 0 && i < value.Length - 1; i++)
{
if(value[i] == '(')
c++;
else if(value[i] == ')')
c--;
}
if(isValid && i == (value.Length - 1) && c == 0)
value = value.Substring(1, value.Length - 2);
This extension method should work;
public static class StringExtensions
{
public static string RemoveParentheses(this string value)
{
if (value == null || value[0] != '(' || value[value.Length - 1 ] != ')') return value;
var cantrim = false;
var openparenthesesIndex = new Stack<int>();
var count = 0;
foreach (char c in value)
{
if (c == '(')
{
openparenthesesIndex.Push(count);
}
if (c == ')')
{
cantrim = (count == value.Length - 1 && openparenthesesIndex.Count == 1 && openparenthesesIndex.Peek() == 0);
openparenthesesIndex.Pop();
}
count++;
}
if (cantrim)
{
return value.Trim(new[] { '(', ')' });
}
return value;
}
}
Use it like this
Console.WriteLine("(text (text) ) text (text)".RemoveParentheses());
Ran a few test cases and I think this is good
public string CleanString(string CleanMe)
{
if (string.IsNullOrEmpty(CleanMe)) return CleanMe;
string input = CleanMe.Trim();
if (input.Length <= 2) return input;
if (input[0] != '(') return input;
if (input[input.Length-1] != ')') return input;
int netParen = 1; // starting loop at 1 have one paren already
StringBuilder sb = new StringBuilder();
for (int i = 1; i < input.Length-1; i++)
{
char c = input[i];
sb.Append(c);
if (c == '(') netParen++;
else if (c == ')') netParen--;
if (netParen == 0) return input; // this is the key did the () get closed out
}
return sb.ToString();
}
I started this before the answer from Amit but I think it is the same basic logic
What's wrong with my code? If I enter aaa, it returns 3 in the vowels row, but if I enter abc, it return 3 also in the vowels row.
By the way, it's a windows form .
txtInputString.SelectionStart = 0;
txtInputString.SelectionLength = txtInputString.Text.Length;
txtInputString.Focus();
int vowelCount = 0, consonants = 0, nonNumeric = 0;
int count = txtInputString.TextLength;
for (int i = 0; i < count; i++)
{
if ((txtInputString.Text.Contains('a') == true) || (txtInputString.Text.Contains('e') == true) || (txtInputString.Text.Contains('i')== true) || (txtInputString.Text.Contains('o')==true) || (txtInputString.Text.Contains('u')==true))
{
vowelCount++;
}
else if ((txtInputString.Text.Contains('b') == true) || txtInputString.Text.Contains('c') || txtInputString.Text.Contains("d") || txtInputString.Text.Contains("f") || txtInputString.Text.Contains("g"))
{
consonants++;
}
else
{
nonNumeric++;
}
}
txtVowel.Text = vowelCount.ToString() + "";
txtConsonant.Text = consonants.ToString() + "";
txtNonNumeric.Text = nonNumeric.ToString();
Try that :
txtInputString.SelectionStart = 0;
txtInputString.SelectionLength = txtInputString.TextLength;
txtInputString.Focus();
int vowelCount = 0, consonants = 0, nonNumeric = 0;
int count = txtInputString.TextLength;
for (int i = 0; i < count; i++)
{
char c = txtInputString.Text.ElementAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
vowelCount++;
else if (c == 'b' || c =='c' || c == 'd' || c == 'f')
consonants++;
else
nonNumeric++;
}
txtVowel.Text = vowelCount.ToString() + "";
txtConsonant.Text = consonants.ToString() + "";
txtNonNumeric.Text = nonNumeric.ToString();
you can make this a lot more simple by loading up all your consonants and vowels beforehand and applying some LINQ:
string consonants = "bcdfghjklmnpqrstvwxyz";
string vowels = "aeiou";
int vowelCount = 0, consonantCount = 0, nonNumericCount = 0;
var input = "alsdkghanivhusrvndb"; //some input
foreach (char t in input)
{
if (consonants.Any(c => c == t))
consonantCount++;
else if (vowels.Any(c => c == t))
vowelCount++;
else
nonNumericCount++;
}
I am trying to read the data in a text file which is separated by commas. My problem, is that one of my data pieces has a comma within it. An example of what the text file looks like is:
a, b, "c, d", e, f.
I want to be able to take the comma between c and d and change it to a semicolon so that I can still use the string.Split() method.
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine ()) != null) {
bool firstQuote = false;
for (int i = 0; i < line.Length; i++)
{
if (line [i] == '"' )
{
firstQuote = true;
}
else if (firstQuote == true)
{
if (line [i] == '"')
{
break;
}
if ((line [i] == ','))
{
line = line.Substring (0, i) + ";" + line.Substring (i + 1, (line.Length - 1) - i);
}
}
}
Console.WriteLine (line);
}
I am having a problem. Instead of producing
a, b, "c; d", e, f
it is producing
a, b, "c; d"; e; f
It is replacing all of the following commas with semicolons instead of just the comma in the quotes. Can anybody help me fix my existing code?
Basically if you find a closing " you recognize it as it was an opening quote.
Change the line:
firstQuote = true;
to
firstQuote = !firstQuote;
and it should work.
You need to reset firstquote to false after you hit the second quote.
else if (firstQuote == true) {
if (line [i] == '"') {
firstquote = false;
break;
}
Here is a simple application to get the required result
static void Main(string[] args)
{
String str = "a,b,\"c,d\",e,f,\"g,h\",i,j,k,l,\"m,n,o\"";
int firstQuoteIndex = 0;
int secodQuoteIndex = 0;
Console.WriteLine(str);
bool iteration = false;
//String manipulation
//if count is even then count/2 is the number of pairs of double quotes we are having
//so we have to traverse count/2 times.
int count = str.Count(s => s.Equals('"'));
if (count >= 2)
{
firstQuoteIndex = str.IndexOf("\"");
for (int i = 0; i < count / 2; i++)
{
if (iteration)
{
firstQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
}
secodQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
string temp = str.Substring(firstQuoteIndex + 1, secodQuoteIndex - (firstQuoteIndex + 1));
firstQuoteIndex = secodQuoteIndex + 1;
if (count / 2 > 1)
iteration = true;
string temp2= temp.Replace(',', ';');
str = str.Replace(temp, temp2);
Console.WriteLine(temp);
}
}
Console.WriteLine(str);
Console.ReadLine();
}
Please feel free to ask in case of doubt
string line = "a,b,mc,dm,e,f,mk,lm,g,h";
string result =replacestr(line, 'm', ',', ';');
public string replacestr(string line,char seperator,char oldchr,char newchr)
{
int cnt = 0;
StringBuilder b = new StringBuilder();
foreach (char chr in line)
{
if (cnt == 1 && chr == seperator)
{
b[b.ToString().LastIndexOf(oldchr)] = newchr;
b.Append(chr);
cnt = 0;
}
else
{
if (chr == seperator)
cnt = 1;
b.Append(chr);
}
}
return b.ToString();
}
I have a textbox where the user enters a random string. I want to count the number of vowels(A,E,I,O,U) in the string and show th results in the labelcontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string EnterString;
EnterString = TextBox1.Text;
char ch1 = 'a';
char ch2 = 'e';
char ch3 = 'i';
char ch4 = 'o';
char ch5 = 'u';
int counta = 0;
int counte = 0;
int counti = 0;
int counto = 0;
int countu = 0;
char ch6 = 'A';
char ch7 = 'E';
char ch8 = 'I';
char ch9 = 'O';
char ch10 = 'U';
int countA = 0;
int countE = 0;
int countI = 0;
int countO = 0;
int countU = 0;
//const string vowels = "aeiou";
/* return value.Count(chr => vowels.Contains(char.ToLower(chr)));
return Value.Count()*/
int j = counta + counte + counti + counto + countu + countA + countE + countI + countO + countU;
foreach (char v in EnterString)
{
if (v == ch1) { counta++; j++; }
else if (v == ch2) { counte++; j++; }
else if (v == ch3) { counti++; j++; }
else if (v == ch4) { counto++; j++; }
else if (v == ch5) { countu++; j++; }
}
foreach (char v in EnterString)
{
if (v == ch6) { countA++; j++; }
else if (v == ch7) { countE++; j++; }
else if (v == ch8) { countI++; j++; }
else if (v == ch9) { countO++; j++; }
else if (v == ch10) { countU++; j++; }
}
Label1.Text = j.ToString();
}
You have this in your code:
const string vowels = "aeiou";
return value.Count(chr => vowels.Contains(char.ToLower(chr)));
That works, at least if your culture is US. So no idea why you commented it out in favor of the current monstrosity.
On a Turkish locale it will fail because the lower case of I is not i but ı (undotted). So if you define vowels as aeiouAEIOU you should use ToLowerInvariant.
But if you want to include other vowels (like Ä) I have no idea how to do that except by listing all the characters.
Full implementation:
int CountVowels(string value)
{
const string vowels = "aeiou";
return value.Count(chr => vowels.Contains(char.ToLowerInvariant(chr)));
}
Looks like you got the good code part from:
Counting vowels using switch
int vowel = 0;
Console.WriteLine("Please enter the string:");
string main = Console.ReadLine();
for (int j = 0; j < main.Length ; j++)
{
if (main[j] == 'a' || main[j] == 'A' || main[j] == 'e' || main[j] == 'E' || main[j] == 'i' || main[j] == 'I' || main[j] == 'o' || main[j] == 'O' || main[j] == 'u' || main[j] == 'U')
{
vowel++;
}
}
Console.WriteLine("Number of vowels in sentence is :"+ vowel);
Console.ReadLine();
Console.WriteLine("Please input your text: ")
mystring = Console.ReadLine
For i = 1 To mystring.Length
Console.Write((mystring(i - 1)) & ",")
isItAVowel = False
If mystring(i - 1) = "a" Or mystring(i - 1) = "A" Then isItAVowel = True
If mystring(i - 1) = "e" Or mystring(i - 1) = "E" Then isItAVowel = True
If mystring(i - 1) = "i" Or mystring(i - 1) = "I" Then isItAVowel = True
If mystring(i - 1) = "o" Or mystring(i - 1) = "O" Then isItAVowel = True
If mystring(i - 1) = "u" Or mystring(i - 1) = "U" Then isItAVowel = True
If isItAVowel Then
This could help good luck
private void button1_Click(object sender, EventArgs e)
{
string EnterString;
EnterString = textBox1.Text;
const string vowels = "aeiou";
label1.Text = EnterString.Count(myString => vowels.Contains(char.ToLowerInvariant(myString))).ToString();
}
public static void Main()
{
char[] sentence = new char[100];
int i, vowels = 0, consonants = 0, special = 0, n;
Console.WriteLine("Enter the Length of the sentence \n");
n = int.Parse(Console.ReadLine());
for (i = 0; i < n; i++)
{
sentence[i] = Convert.ToChar(Console.Read());
}
for (i = 0; sentence[i] != '\0'; i++)
{
if ((sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] ==
'i' || sentence[i] == 'o' || sentence[i] == 'u') ||
(sentence[i] == 'A' || sentence[i] == 'E' || sentence[i] ==
'I' || sentence[i] == 'O' || sentence[i] == 'U'))
{
vowels = vowels + 1;
}
else
{
consonants = consonants + 1;
}
if (sentence[i] == 't' || sentence[i] == '\0' || sentence[i] == ' ')
{
special = special + 1;
}
}
consonants = consonants - special;
Console.WriteLine("No. of vowels {0}", vowels);
Console.WriteLine("No. of consonants {0}", consonants);
Console.ReadLine();
Console.ReadLine();
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
set<char> vowels = {'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'};
while(t--)
{
string s;
int c = 0;
cin >> s;
for(char i : s)
if(vowels.find(i) != vowels.end())
++c;
cout << c << "\n";
}
return 0;
}
string vowelList = ("aeiouAEIOU");
int i = 0;
int j = 0;
int vowelCount = 0;
string main = textBox1.Text; /or Console.ReadLine();
while (j < main.Length)
{
while (i < vowelList.Length)
{
if (main[j] == vowelList[i])
{
vowelCount++;
}
i++;
}
j = j + 1;
i = 0;
}
label1.Text = ("Number of vowels in sentence is :" + vowelCount); /or Console.Writeline ("Number of vowels in sentence is: " + vowelCount
count = 0
string=input("Enter string:")
vowels = set("aeiouAEIOU")
for letter in string:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)