【问题标题】:trim last character if not a number如果不是数字,则修剪最后一个字符
【发布时间】:2017-07-10 03:25:50
【问题描述】:

如果不是数字,我正在尝试从字符串中删除最后一个字符 例如:“2+3-4*” 从那里最后一个 astrik 需要被修剪,因为它不是数字我的结果应该是“2+3-4”。如果用户输入“2+3+8”则不需要修剪,因为最后是数字。

【问题讨论】:

  • 我不认为这完全是一个骗局,只是高度相关。 OP 不一定知道他们要修剪的角色是什么,因此它确实涉及到比仅仅修剪特定角色更多的智能。
  • 我在这里必须同意@DangerZone - 这不是那个问题的欺骗。
  • 另外,答案似乎存在分歧。如果有多个尾随非数字怎么办? (例如,"2+3-4**")。是否应该同时删除 *,还是只删除最后一个?
  • @DangerZone 就是这样,看来 OP 忽略了这种情况。一旦意识到所选答案有这个问题,可能OP会在一段时间内再次出现......

标签: c#


【解决方案1】:

您可以使用这个正则表达式:[^0-9]$ 来确定最后一个字符是否是其他而不是数字。如果正则表达式匹配,只需删除最后一个字符。

string a = "abc";
if (Regex.IsMatch(a, "[^0-9]$"))
{
  a = a.Remove(a.Length - 1);
}

【讨论】:

  • 为什么当它只删除一个字符时会得到更多的爱,一旦你匹配了你想要的,不使用正则表达式替换有什么意义......我会理解,作为其他回答者, 没有正则表达式可以解决它......但是为什么要混合两种方法呢?无论如何,它只会丢弃一个非数字字符...
  • @MatíasFidemraizer - 我不明白你的最后一句话。根据问题,它应该只删除一个非数字字符。
  • @DangerZone 仅 一个。
  • @MatíasFidemraizer OP 指定他只想删除一个字符。此外,您可以根据需要使此匹配多个字符。
【解决方案2】:

您可以使用下面的 sn-p 检查最后一个字符是否为数字:

例如:

string value = "4+8-4*";
int outInt = 0;
bool isLastCharNumeric = int.TryParse(value[value.Length - 1].ToString(), out outInt);
if (!isLastCharNumeric)
{
    //chop off the last char
    value = value.Remove(value.Length - 1;);
}

【讨论】:

  • @VenkateshKonduru - 请注意,如果您需要删除多个非数字字符,这将不起作用。这只会删除最后一个。
  • 正确,但是您的问题确实指出,“如果不是数字,我会尝试从字符串中删除最后一个字符”
【解决方案3】:

您可以抓取最后一个字符并检查它是否为数字,如果是则删除。

string str = "2+3-4*";

if(!Char.IsNumber(str[str.Length - 1])){
  str = str.Remove(str.Length - 1);
}

【讨论】:

    【解决方案4】:

    使用正则表达式:

    string str= "2+3-4*";
    str = Regex.Replace(str, "[^0-9]$", "");
    

    【讨论】:

      【解决方案5】:

      或许你可以使用正则表达式:

      string input = "2+3+";
      // Regexp => one or more occurences of a non-numeric character at
      // the end of the string
      string santizedInput = Regex.Replace(input, "[^0-9]+$", "");
      

      【讨论】:

        【解决方案6】:

        我会使用正则表达式。 [^\d]+$

        查看结果:https://regex101.com/r/pE0h48/1

        【讨论】:

          【解决方案7】:

          我认为正则表达式是解决这个问题的好方法。

          Regex rgx = new Regex("\D+$");
          string result = rgx.Replace("2+3-4*", "");
          

          【讨论】:

            【解决方案8】:

            我的方法是使用正则表达式,但不是使用它来替换最后一个字符,而是使用正则表达式来提取字符串的有效部分。我的方法是用 Java 编写的,但您可以很容易地将其转换为 C#。

            Pattern pattern = Pattern.compile("([0-9]+)([\\+\\-\\:\\*][0-9])+");
            Matcher m;
            String input = "++2+4+5-6*3+4*2-3--";
            m = pattern.matcher(input);
            while(m.find()){
                System.out.println(m.group());
            }
            

            【讨论】:

              【解决方案9】:

              我不喜欢正则表达式,因为它们相对来说很慢。我们可以很容易地解决这个问题,方法是定义数字是什么,然后检查最后一个字符是否是其中之一。所以首先让我们通过指定我们认为是数字的内容来打开。

              static readonly char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
              

              现在我们需要根据最后一个字符是否是我们刚刚列出的字符之一返回两个结果之一。为此,我们使用三元语句。

              var testInput = "testing5";//Testing input
              var trimmedString = 
                  numbers.Any(x => x == testInput[testInput.Length - 1]) ?//testInput.Length - 1 is going to give us the last character in the string
                  testInput : //It's a number so go ahead and return the full string
                  testInput.SubString(0, testInput.Length - 1);//It's not a number so lets return all but the last character in the string as a new string.
              

              所以我们的最终产品看起来像这样。我将它封装到一个方法中,因为它是您代码的一个非常独立的方面(大概)。

              static readonly char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
              
              public static string TrimNonNumbers(string input)
              {
                  if (string.IsNullOrEmpty(input)) return input;//Our math will produce an index out of range exception with an empty string.  So this is a safety to prevent that.
                  return numbers.Any(x => x == testInput[testInput.Length - 1]) ? testInput : testInput.SubString(0, testInput.Length - 1);
              }
              

              【讨论】:

                【解决方案10】:

                工作的、经过测试的代码

                using System;
                
                public class Program
                {
                    public static void Main()
                    {
                        string calculation = "2+3+81%";
                        int length = calculation.Length;
                        if(!Char.IsNumber(calculation[length-1])){
                            calculation = calculation.TrimEnd(calculation[length-1]);
                        }
                        Console.Write(calculation);
                    }
                }
                

                【讨论】:

                • 为什么要检查大于字符串本身长度的位置的字符?这会导致每次都抛出异常。
                • 我把一些东西弄混了,它未经测试的伪代码很难。修好了。
                猜你喜欢
                • 2018-07-08
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-04-04
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多