A
A
Andrey Zagorodniy2017-09-23 23:48:37
C++ / C#
Andrey Zagorodniy, 2017-09-23 23:48:37

How to check if there are characters 2 or 3 or 4 ... or 9 in a string array?

There is a code for converting to decimal with binary. I checked that there were current digits, but how to weed out all the digits except 1 and 0?
Here is the code:

string bin = "t";
            bool result;
            int number, dec;
            dec = 0;
            Console.WriteLine("Enter number!");
            do
            {
                bin = Console.ReadLine();
                result = Int32.TryParse(bin, out number);
                if (result)
                {
                    dec = Convert.ToInt32(bin, 2);
                }
                else
                {
                    Console.WriteLine("Incorrect number.",
                                       bin == null ? "<null>" : bin);
                }
            } while (!result);

            Console.WriteLine(dec);
            Console.ReadKey();

It seems that you can do it so that the cell function of the string array checks and sees if there are numbers from 2 to 9

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2017-09-24
@kttotto

Weed out or replace with something - there is a Replace () method
Accordingly
Since this method replaces only one value at a time, you will either have to do Replace(...).Replace(..)... several times, or write your own method that will do this in a loop. Some extension:

public static class StrExtantion
  {
    public static string ReplaceDigits(this string str, IEnumerable<int> digits)
    {
      var temp = string.Copy(str);
      foreach (var digit in digits)
      {
        temp = temp.Replace(digit.ToString(), string.Empty);
      }
      return temp;
    }
  }

And then use it:
But you can do it in one line:
string temp = string.Copy(result); 
Enumerable.Range(2, 8).ToList().ForEach(x => temp = temp.Replace(x.ToString(), string.Empty));
Console.WriteLine(temp);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question