简体   繁体   English

如何从带有空格的字符串中删除最后一个字符

[英]How to remove the last character from a string with white spaces

I am creating a calculator app with a backspace button, and I need to remove the characters that are not spaces. 我正在使用退格按钮创建一个计算器应用程序,并且需要删除不是空格的字符。

Say I have a string such as: 说我有一个字符串,例如:

String s = "1 + 2 - 3";

I want to be able to click the button and have it remove 'o' first. 我希望能够单击该按钮,然后先将其删除。 If I click the button again, instead of removing the space after the '-', I want to remove the '-' itself, etc. 如果我再次单击该按钮,则想删除“-”本身,而不是删除“-”之后的空格。

I initially tried something like: 我最初尝试过类似的方法:

s = s.replaceAll(" ", "");
s = s.substring(0,field.length()-1);
s = s.replaceAll("", " ").trim();

The only reason I need the whitespace is that there is a class that evaluates the expression and requires the white space to evaluate it correctly. 我需要空白的唯一原因是,有一个用于评估表达式的类,并且需要空白才能正确评估它。

With what I have right now, if I were to click backspace and delete '3', then click another button like 2, what I get is: 现在,如果我单击退格键并删除“ 3”,然后单击另一个按钮(如2),则得到的是:

"1 + 2 -2"

However, what I want is: 但是,我想要的是:

"1 + 2 - 2" 

The trick would be to use .trim() when you remove a char to also remove the space : 技巧是在删除字符时也使用.trim()来删除空格:

static String removeAChar(String s) { //1st trim() to be sure, 2nd trim() to remove extra space
    return s.trim().substring(0, s.length() - 1).trim();
}

And this would give : 这将给:

public static void main(String[] args) {
    String s = "h e l l o";
    System.out.println(s);
    for (int i = 0; i < 4; i++) {
        s = removeAChar(s);
        System.out.println(s);
    }
}
/*
h e l l o
h e l l
h e l
h e
h

Trim method will remove all the leading whitespaces also. 修剪方法也将删除所有前导空格。 So if you have " hello" it will remove the first space before "h". 因此,如果您具有“ hello”,它将删除“ h”之前的第一个空格。 If you don't want that, here is a solution 如果您不想要,这是一个解决方案

public static String RemoveLastNotSpaceChar(String str){
      if(str==null)
          return null;
      str = removeTrailingSpaces(str);
      if(str.length()>0)
          return str.substring(0, str.length() - 1);
      return "";
}

public static String removeTrailingSpaces(String param) 
    {
        if (param == null)
            return null;
        int len = param.length();
        for (; len > 0; len--) {
            if (!Character.isWhitespace(param.charAt(len - 1)))
                break;
        }
        return param.substring(0, len);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM