0

I want go through a string, and check if in the string is a char available. For example: My string is: string test = "100+20+3-17+2" So now I go through my string and check the chars:

List<string> numbers= new List<string>();
foreach( char c in test)
{
   if (c =='+'|| c =='-'||c =='/'||c =='*')
   {
     //Now here i want to save all chars before '+' '-'  '/'  '*' in my list numbers. in this example: save 100, 20,3,17,2 in my list
   }
}

How would you do this?

mmvsbg
  • 3,570
  • 17
  • 52
  • 73
saaami11
  • 109
  • 2
  • 2
  • 8
  • _"here i want to save all chars"_ what means _save_? Is it important to save the pairs which belong to specific characters like in `100+20` or doesn't it matter if you don't know later to which character they belonged, like in `100+20/30`? – Tim Schmelter Jun 17 '15 at 07:34
  • @Tim Schmelter No i want know later which character will be entered. But i want further than total the whole numbers.. I think that will be very difficult – saaami11 Jun 17 '15 at 08:10

4 Answers4

2

just split your string with the characters

List<string> numbers = new List<string>();
string test = "100+20+3-17+2";
char[] chars = new char[] { '+', '-', '*', '/' };
numbers = test.Split(chars).ToList();
fubo
  • 44,811
  • 17
  • 103
  • 137
1

I'd go with a StringBuilder. As you go through the original string to check chars add them to the StringBuilder. When you find a splitter char add StringBuilder.ToString in the list and empty the StringBuilder.

The code should look something like the following (haven't tested it):

List<string> numbers= new List<string>();
StringBuilder sb = new StringBuilder();

foreach( char c in test)
{
    if (c =='+'|| c =='-'||c =='/'||c =='*')
    {
        //Now here i want to save all chars before '+' '-'  '/'  '*' in my list numbers. in this example: save 100, 20,3,17,2 in my list

        numbers.Add(sb.ToString());
        sb.Clear();
    }
    else
    {
        sb.Append(c);
    }
}
Gentian Kasa
  • 776
  • 6
  • 10
1

If char not in '+', '-', '/', '*', you can concat the chars in string. When operator comes you can add the sting to list, and empty string

List<string> numbers= new List<string>();
string curNumber="";
foreach( char c in test)
{
   if (c =='+'|| c =='-'||c =='/'||c =='*')
   {
     numbers.Add(curNumber);
     curNumber="";
   }
   else
   {
     //also you can add operators in other list here
     curNumber+=c.ToString();
   }
}
numbers.Add(curNumber);
  • Like i ask above, but now if i want total the numbers, how can i work furhter with the numbers? The result in this example is 108? – saaami11 Jun 17 '15 at 07:59
0

use String.Split(Char[]) to get an array of the splitted string

  • "this" isn't very descriptive, you should include the relevant information from that link in your answer. If the link were to die, then so would your answer – Sayse Jun 17 '15 at 07:33