I want to create a program that takes in a string and output just the numbers, hopefully using regex to save effort, here is the following code i have
public void main{
string str = "abc-123.44def";
string output = "";
bool setA = false;
StringBuilder stb = new StringBuilder();
for(int i=0; i<str.Length; i++){
switch(str[i]){
case 'b':
setA = foo();
break;
case 'c':
foo2();
break;
case '\d':
case '-':
case '.':
if(setA){
stb.Append(str[i]);
}
break;
default:
break;
}
}
output = stb.toString();
}
public void foo(){
return true;
}
Problem is, the editor gives me a error saying
Unrecognized Escape Sequence
on the '\d' part. Ive seen online sample codes where such usage is allowed so im not sure why my editor is not accepting this. Can someone explain to me what the problem is and how to solve it?
EDIT: It seems like my sample was alittle misleading. I cannot just take out the numbers from the strings by itself since other characters in the string calls different functions and the number characters i want to take out depends on some of them. I updated the code to correct the misinformation.
You can use the Char.IsDigit() to check if a char is a digit (as I mentioned in my first comment):
string str = "abc-123.44def";
string output = "";
bool setA = false;
StringBuilder stb = new StringBuilder();
for(int i=0; i<str.Length; i++){
switch(str[i]){
case 'b':
setA = foo();
break;
case 'c':
foo2();
break;
// case '\d': REMOVE IT
case '-':
case '.':
if(setA){
stb.Append(str[i]);
}
break;
default:
if (Char.IsDigit(str[i])) stb.Append(str[i]); // Add this
break;
}
}
output = stb.ToString();
}
Result:
Is this what you are looking for ?
Regex r = new Regex(#"\d+");
string s = "abc-123.44def";
var matches = r.Matches(s);
List<string> numbersOnly = new List<string>();
foreach (Match match in matches)
numbersOnly.Add(match.Value);
foreach (var number in numbersOnly)
Console.WriteLine(number);
//output:
//123
//44
Related
Hit everyone! I'm still learning C# and I would like to print different string for each loop based on the switch cases.
static Random rand = new Random();
static void Main(string[] args){
string someString = "";
int someRandom = rand.Next(4);
switch(someRandom) {
case 0:
someString = "Woa";
break;
case 1:
someString = "Waa";
break;
case 2:
someString = "Wee";
break;
case 3:
someString = "Wow!";
break;
}
int someCount = 5;
for (int someInt = 0; someInt < someCount; someInt++) {
Console.WriteLine(someString);
}
Console.Read();
}
What it should do: display random string each loop from the switch.
What it actually does: Selects case randomly and prints the same case in each loop.
I couldn't produce a random string, why is that? I tried adding someRandom = rand.Next(4) inside the for loop but still produces same.
I already tried searching but couldn't find an answer that could solve my problem.
It seems that you are only setting somestring once, and then printing it a bunch. You should put the switch statement in the for loop.
You need to generate the random number (and set the someString variable) inside the loop, otherwise you only pick one random number and then display it multiple times in the loop.
Here's an example but with some slightly better names (IMO):
static Random rand = new Random();
static void Main()
{
int count = 5;
for (int i = 0; i < count; i++)
{
string output;
switch(rand.Next(4))
{
case 0:
output = "Woa";
break;
case 1:
output = "Waa";
break;
case 2:
output = "Wee";
break;
case 3:
output = "Wow!";
break;
default:
output = "This shouldn't happen";
break;
}
Console.WriteLine(output);
}
Console.Read();
}
I'm using a portion of C# code from Sanjit Prasad to solve the challenge of processing backspaces in a given string of words. The new challenge is to process the left-arrow-key and right-arrow-key in combination with backspaces, reflecting a "corrector" for typos in writing.
The following string represents the problem and solution for the first challenge using a FIFO stack (credits to Sanjit Prasad):
string: thiss# is a txt##ext with some typos
expected result: this is a text with some typos
This is the code to generate the expected result:
static String finalAnswer(String S)
{
Stack<Char> q = new Stack<Char>();
for (int i = 0; i < S.Length; ++i)
{
if (S[i] != '#') q.Push(S[i]);
else if (q.Count!=0) q.Pop();
}
String ans = "";
while (q.Count!=0)
{
ans += q.Pop();
}
String answer = "";
for(int j = ans.Length - 1; j >= 0; j--)
{
answer += ans[j];
}
return answer;
}
That code works great, now, the challenge is to process the following string:
string: ths#is is an te\\\#///xt wit some\\\\\h///// tpos###ypos
expected result: this is a text with some typos
In the above string, the character "\" represents a left arrow key pressed, and "/" a right arrow key pressed.
Thank you so much for all your comments, this is my very first question in Stackoverflow, I would like to know an approach to solve the this challenge.
Here is a version that gets the job done, but will need some checks for edge cases and some more error checks.
static string GenerateUpdatedString(string strInput)
{
var stringStack = new Stack<char>();//holds the string as it is read from the input
var workingStack = new Stack<char>();//hold chars when going back to fix typos
char poppedChar;
foreach (var ch in strInput)
{
switch (ch)
{
case '\\':
{
PushAndPopCharacters(workingStack, stringStack);
break;
}
case '/':
{
PushAndPopCharacters(stringStack, workingStack);
break;
}
case '#':
{
stringStack.TryPop(out poppedChar);
break;
}
default:
stringStack.Push(ch);
break;
}
}
return new string(stringStack.Reverse().ToArray());
}
static void PushAndPopCharacters(Stack<char> stackToPush, Stack<char> stackToPop)
{
char poppedChar;
if (stackToPop.TryPop(out poppedChar))
{
stackToPush.Push(poppedChar);
}
}
Usage
var result = GenerateUpdatedString
(#"ths#is is an te\\\#///xt wit some\\\\\h///// tpos###ypos");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am a novice C# user, and I am experimenting with lists in Csharp's console application. This list contains 10 numbers, and the order of these numbers are randomized. What I want to do is to make specific text for a specific number which if statements will handle.
For example: If number == 0, the text "Hello" will show up. Or if the number == 3, the text "Goodbye" will show up.
I tried a few things but I got problems like repeated text: http://i.imgur.com/8sCbeLn.jpg?1
Random r = new Random();
int tempValue;
List<int> number = new List<int>();
number.Add(0);
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
for (int i = 0; i < 10; i++)
{
tempValue = r.Next(0, number.Count);
Console.WriteLine(number[tempValue]);
number.RemoveAt(tempValue);
Console.ReadLine();
}
Please help me getting on the right track.
You can for example use a switch to select strings from a value.
If you get repeated values, I suspect that you used tempValue to select the string, you have to use number[tempValue]:
string text = null;
switch (number[tempValue]) {
case 0: text = "Hello"; break;
case 1: text = "How do you do"; break;
case 2: text = "Howdie"; break;
case 3: text = "Goodbye"; break;
case 4: text = "Bye"; break;
case 5: text = "Hello again"; break;
case 6: text = "Good day"; break;
case 7: text = "Have fun"; break;
case 8: text = "Greatings"; break;
case 9: text = "Goodbye again"; break;
}
Why not add 10 random numbers to a list and then loop through the list, and print using you if statements
Random r = new Random();
List<int> nums= new List<int>();
int numForList = r.Next(0,10);
bool numInList = true;
//add 10 random numbers to a list
for(int i=0;i<10;i++)
{
do
{
if(!nums.Contains(numForList))
{
numInList = false;
nums.Add(numForList);
}
else
{
numForList = r.Next(0,10);
}
} while (numInList == true);
numInList = true;
}
foreach(var num in nums)
{
switch (num)
{
case 0: Console.WriteLine("Hello"); break;
case 1: Console.WriteLine("How do you do"); break;
... //Add more cases here for each possible random number
}
}
I'm implementing a filter.
I store the filter criteria in a list of string. e.g.
List filters
A filter logic as a string e.g.
String filterLogic = "(1 AND 2) OR 3";
Now I want to replace the numbers with the filter criteria, e.g.
(filters[1] AND filters[2]) OR filters[3])
//stores all the filter criterias
List<String> filters = new List<string>();
for (int i = 1; i <= controlGroupId;i++ )
{
StringBuilder sb = new StringBuilder();
String fieldsDropdownId="dlFields"+i;
DropDownList dlFields = (DropDownList)this.FindControl(fieldsDropdownId);
sb.Append(dlFields.SelectedValue);
String operatorDropdownId = "dlOperator" + i;
DropDownList dlOperator = (DropDownList)this.FindControl(operatorDropdownId);
String operatorValue = dlOperator.SelectedValue;
String valuetxbId = "txb" + i;
TextBox tb = (TextBox)this.FindControl(valuetxbId);
String textboxValue = tb.Text;
switch (operatorValue)
{
case "=":
sb.Append("=");
sb.Append(textboxValue);
break;
case "<>":
sb.Append("<>");
sb.Append(textboxValue);
break;
case "<":
sb.Append("<");
sb.Append(textboxValue);
break;
case ">":
sb.Append(">");
sb.Append(textboxValue);
break;
case ">=":
sb.Append(">=");
sb.Append(textboxValue);
break;
case "<=":
sb.Append("<=");
sb.Append(textboxValue);
break;
case "contains":
sb.Append(" Like ");
sb.Append("'%");
sb.Append(textboxValue);
sb.Append("%'");
break;
case "does not contain":
sb.Append(" Not Like ");
sb.Append("'%");
sb.Append(textboxValue);
sb.Append("%'");
break;
case "starts with":
sb.Append(" Like ");
sb.Append("'");
sb.Append(textboxValue);
sb.Append("%'");
break;
}
filters.Add(sb.ToString());
}
Update:
List<String> l = new List<string>();
for (int i = 1; i < 12; i++)
{
String s="hello"+i;
l.Add(s);
}
String ss = "(1 AND 2 AND 3 AND 4 AND 5 AND 6 AND 7 AND 8 AND 9 AND 10 AND 11)";
Regex rgx = new Regex(#"\d+");
ss=rgx.Replace(ss, "l[$0]");
This gives me :
"(l[1] AND l[2] AND l[3] AND l[4] AND l[5] AND l[6] AND l[7] AND l[8] AND l[9] AND l[10] AND l[11])"
What I want is:
(hello1 AND hello2 AND hello3 AND hello4 AND hello5 AND hello6 AND hello7 AND hello8 AND hello9 AND hello10 AND hello11)";
Given all integers are indices, one can do the following:
Regex rgx = new Regex (#"\d+");
rgx.Replace(fitlerLogic, "filters[$0]");
Then the result is:
"filters[1] AND filters[2]) OR filters[3]"
But this only works if all integers should be replaced with filter indices.
You also made by the way a typo: it's filterLogic, not fitlerLogic.
EDIT: or if you want to substitute it with the real value, you can use a lambda-expression:
object[] filter = new object[] {false,true,false,true};//not that an array is 0-indexed
Regex rgx = new Regex (#"\d+");
rgx.Replace (fitlerLogic,x => filter[int.Parse(x.Value)].ToString());
In that case the result is:
"(True AND False) OR True"
If you however wish to evaluate the expression, I would take a look to compiler-compilers and context-free grammars.
Having a string like:
0x1TTTT10TT1Tx01Tx1001xxx100T0TxT1T1TxTxTxx0TT0000000x0xTxT1Tx0T0x10x1
I want to get:
0 appears 20
1 appears 12
x appears 17
T appears 21
If I use
int zero = Regex.Matches(input, "0").Count;
int one = Regex.Matches(input, "1").Count;
int x = Regex.Matches(input, "x").Count;
int T = Regex.Matches(input, "T").Count;
How to accomplish same result using more efficient approach using Regex?
This is not really the real purpose of Regular Expressions. I would instead advise the use of a loop over the characters, like the following:
int zeroCount = 0;
int oneCount = 0;
int xCount = 0;
int tCount = 0;
foreach(var ch in input)
{
switch(ch)
{
case '0':
zeroCount++;
break;
case '1':
oneCount++;
break;
case 'x':
xCount++;
break;
case 'T':
tCount++;
break;
}
}
Unfortunately the most efficient isn't usually the most concise.