Reputation: 67
Hi I know this might be a bit silly. But I need to convert my string to a number, and hence I need to use char to loop through the operators. However if I try to do a two or more digit number the number gets broken into single digits. For example.
string str="2+16-42X"
char[] ch=str.toCharArray();
the output comes as(ignore the commas)
2,+,1,6,-,4,2,X
I want to get 2,+,16,-42,X
any suggestion on how to work around this? Thank you
Upvotes: 1
Views: 931
Reputation: 45947
Here is a RegEx approach
string str = "2+16-42X";
string[] result = Regex.Matches(str, "-?\\d+|[+/*X]")
.Cast<Match>().Select(x => x.Value).ToArray();
explanation:
-?
optional -
character at the beginning\d+
one or more digit |
or[+/*X]
one of these characters +
, /
, *
, X
https://dotnetfiddle.net/d2ZaGC
Upvotes: 4
Reputation: 14007
You can write a simple lexer:
string str="2+16-42X";
StringBuilder currentNumber = new StringBuilder();
List<string> tokens = new List<string>();
foreach(char chr in str) {
if (Char.IsDigit(chr)) {
currentNumber.Append(chr);
}
else {
if (currentNumber.Length > 0) {
tokens.Add(currentNumber.ToString());
currentNumber.Clear();
}
if (chr == '-') {
currentNumber.Append(chr);
}
else {
tokens.Add(chr.ToString());
}
}
}
if (currentNumber.Length > 0) {
tokens.Add(currentNumber.ToString());
}
The tokens
list contains your numbers and symbols.
Upvotes: 4
Reputation: 2437
You can try to use codes below:
string str = "2+16-42X";
str = str.Replace("+", " +");
str = str.Replace("-", " -");
str = str.Replace("X", " X");
var numbers = str.Split(' ');
foreach (var number in numbers)
{
Console.WriteLine(number);
}
Output:
2
+16
-42
X
Upvotes: -3
Reputation: 7479
Use RegEx:
string str="2+16-42X";
var match = Regex.Match(str, @"(\d+|\D)+");
match.Groups[1].Captures.Cast<Capture>().Select(c => c.Value).ToList();
returns:
2,+,16,-,42,X
Upvotes: -4