如何检查数字是在数字的左侧还是右侧

How to check is a number is on left side or right side of number

如何检查数字是在数字的左侧还是右侧

例如数字是 2,我想要它在 12 和 23 上的位置

也就是 2 在 23 的左边,在 12 的右边

我的代码

class Solution
{
   public static  void Main(String[] args)
   { 
      var number =  12;
      foreach(char c in number.ToString()){
         if(c=='2'){
            Console.WriteLine(c);
         }
      }
   }
}
class Solution
{
   public static  void Main(String[] args)
   { 
      bool isLeft = true;
      var number =  12;
      foreach(char c in number.ToString()){
         if(c=='2'){
            if(isLeft)
            {
                Console.WriteLine("It's on the left.");
            }
            else 
            {
               Console.WriteLine("It's on the right");
            }
            Console.WriteLine(c);
         }
     isLeft = false;
      }
   }
}

编辑: 我添加了证据

class Program
    {
        static void Main(string[] args)
        {
            NewMethod(12);
            NewMethod(23);
        }

        private static void NewMethod(int number)
        {
            bool isLeft = true;
            foreach (char c in number.ToString())
            {
                if (c == '2')
                {
                    if (isLeft)
                    {
                        Console.WriteLine("It's on the left.");
                    }
                    else
                    {
                        Console.WriteLine("It's on the right");
                    }
                    Console.WriteLine(c);
                }
                isLeft = false;
            }
        }
    }

证明 un-edited 版本有效:

查看此代码:

CheckNumber(12);
CheckNumber(23);

static void CheckNumber(int number)
{
    var str = number.ToString();
    if (str[0] == '2')
        Console.WriteLine("2 is in left");
    if (str[^1] == '2')
        Console.WriteLine("2 is in right");
}