简体   繁体   English

如何从字符串中删除最后一个字符?

[英]How to remove the last character from a string?

I want to remove the last character from a string.我想从字符串中删除最后一个字符。 I've tried doing this:我试过这样做:

public String method(String str) {
    if (str.charAt(str.length()-1)=='x'){
        str = str.replace(str.substring(str.length()-1), "");
        return str;
    } else{
        return str;
    }
}

Getting the length of the string - 1 and replacing the last letter with nothing (deleting it), but every time I run the program, it deletes middle letters that are the same as the last letter.获取字符串的长度 - 1 并将最后一个字母替换为空(删除它),但是每次我运行程序时,它都会删除与最后一个字母相同的中间字母。

For example, the word is "admirer";例如,这个词是“崇拜者”; after I run the method, I get "admie."运行该方法后,我得到“admie”。 I want it to return the word admire.我希望它返回钦佩这个词。

replace will replace all instances of a letter. replace将替换一个字母的所有实例。 All you need to do is use substring() :您需要做的就是使用substring()

public String method(String str) {
    if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
        str = str.substring(0, str.length() - 1);
    }
    return str;
}

Why not just one liner?为什么不只有一个班轮?

public static String removeLastChar(String str) {
    return removeLastChars(str, 1);
}

public static String removeLastChars(String str, int chars) {
    return str.substring(0, str.length() - chars);
}

Full Code完整代码

public class Main {
    public static void main (String[] args) throws java.lang.Exception {
        String s1 = "Remove Last CharacterY";
        String s2 = "Remove Last Character2";
        System.out.println("After removing s1==" + removeLastChar(s1) + "==");
        System.out.println("After removing s2==" + removeLastChar(s2) + "==");
    }
    
    public static String removeLastChar(String str) {
        return removeLastChars(str, 1);
    }

    public static String removeLastChars(String str, int chars) {
        return str.substring(0, str.length() - chars);
    }
}

Demo演示

因为我们是在一个主题上,所以也可以使用正则表达式

"aaabcd".replaceFirst(".$",""); //=> aaabc  

The described problem and proposed solutions sometimes relate to removing separators.所描述的问题和提出的解决方案有时涉及去除分离器。 If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.如果这是你的情况,那么看看 Apache Commons StringUtils,它有一个名为removeEnd的方法,它非常优雅。

Example:例子:

StringUtils.removeEnd("string 1|string 2|string 3|", "|");

Would result in: "string 1|string 2|string 3"将导致:“字符串 1|字符串 2|字符串 3”

public String removeLastChar(String s) {
    if (s == null || s.length() == 0) {
        return s;
    }
    return s.substring(0, s.length()-1);
}

不要试图重新发明轮子,而其他人已经编写了执行字符串操作的库: org.apache.commons.lang3.StringUtils.chop()

Use this:用这个:

 if(string.endsWith("x")) {

    string= string.substring(0, string.length() - 1);
 }

In Kotlin you can used dropLast() method of the string class.在 Kotlin 中,您可以使用字符串类的 dropLast() 方法。 It will drop the given number from string, return a new string它将从字符串中删除给定的数字,返回一个新字符串

var string1 = "Some Text"
string1 = string1.dropLast(1)
if (str.endsWith("x")) {
  return str.substring(0, str.length() - 1);
}
return str;

For example, the word is "admirer";例如,这个词是“崇拜者”; after I run the method, I get "admie."运行该方法后,我得到“admie”。 I want it to return the word admire.我希望它返回钦佩这个词。

In case you're trying to stem English words如果你想阻止英语单词

Stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form.词干化是将屈折(或有时派生)词简化为词干、词根或词根形式的过程——通常是书面词形式。

... ...

A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem".例如,英语词干分析器应将字符串“cats”(可能还有“catlike”、“catty”等)识别为基于词根“cat”,并将“stemmer”、“stemming”、“stemmed”识别为基于“茎”。 A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".词干提取算法将单词“fishing”、“fished”、“fish”和“fisher”简化为词根“fish”。

Difference between Lucene stemmers: EnglishStemmer, PorterStemmer, LovinsStemmer outlines some Java options. Lucene 词干分析器之间的区别:EnglishStemmer、PorterStemmer、LovinsStemmer概述了一些 Java 选项。

As far as the readability is concerned, I find this to be the most concise就可读性而言,我觉得这是最简洁的

StringUtils.substring("string", 0, -1);

The negative indexes can be used in Apache's StringUtils utility.可以在 Apache 的 StringUtils 实用程序中使用负索引。 All negative numbers are treated from offset from the end of the string.所有负数都从字符串末尾的偏移量开始处理。

public String removeLastChar(String s) {
    if (!Util.isEmpty(s)) {
        s = s.substring(0, s.length()-1);
    }
    return s;
}

removes last occurence of the 'xxx':删除最后一次出现的“xxx”:

    System.out.println("aaa xxx aaa xxx ".replaceAll("xxx([^xxx]*)$", "$1"));

removes last occurrence of the 'xxx' if it is last:删除最后一次出现的 'xxx' 如果它是最后一次:

    System.out.println("aaa xxx aaa  ".replaceAll("xxx\\s*$", ""));

you can replace the 'xxx' on what you want but watch out on special chars您可以根据需要替换“xxx”,但要注意特殊字符

 string = string.substring(0, (string.length() - 1));

I'm using this in my code, it's easy and simple.我在我的代码中使用它,它简单易行。 it only works while the String is > 0. I have it connected to a button and inside the following if statement它仅在字符串 > 0 时有效。我将它连接到一个按钮并在以下if语句中

if (string.length() > 0) {
    string = string.substring(0, (string.length() - 1));
}
 // creating StringBuilder
 StringBuilder builder = new StringBuilder(requestString);
 // removing last character from String
 builder.deleteCharAt(requestString.length() - 1);

Look to StringBuilder Class :看看 StringBuilder 类:

    StringBuilder sb=new StringBuilder("toto,");
    System.out.println(sb.deleteCharAt(sb.length()-1));//display "toto"

How can a simple task be made complicated.一个简单的任务如何变得复杂。 My solution is:我的解决办法是:

public String removeLastChar(String s) {
    return s[0..-1]
}

or要么

public String removeLastChar(String s) {
    if (s.length() > 0) {
        return s[0..-1]
    }
    return s
}

一个单一的答案(只是一个有趣的选择- 不要在家里尝试这个,已经给出了很好的答案):

public String removeLastChar(String s){return (s != null && s.length() != 0) ? s.substring(0, s.length() - 1): s;}
// Remove n last characters  
// System.out.println(removeLast("Hello!!!333",3));

public String removeLast(String mes, int n) {
    return mes != null && !mes.isEmpty() && mes.length()>n
         ? mes.substring(0, mes.length()-n): mes;
}

// Leave substring before character/string  
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));

public String leaveBeforeChar(String mes, String last) {
    return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
         ? mes.substring(0, mes.lastIndexOf(last)): mes;
}

Most answers here forgot about surrogate pairs .这里的大多数答案都忘记了代理对

For instance, the character 𝕫 (codepoint U+1D56B) does not fit into a single char , so in order to be represented, it must form a surrogate pair of two chars.例如,字符 𝕫(代码点 U+1D56B)不适合单个char ,因此为了表示,它必须形成两个字符的代理对。

If one simply applies the currently accepted answer (using str.substring(0, str.length() - 1) , one splices the surrogate pair, leading to unexpected results.如果简单地应用当前接受的答案(使用str.substring(0, str.length() - 1) ,则会拼接代理对,导致意外结果。

One should also include a check whether the last character is a surrogate pair:还应该包括检查最后一个字符是否是代理对:

public static String removeLastChar(String str) {
    Objects.requireNonNull(str, "The string should not be null");
    if (str.isEmpty()) {
        return str;
    }

    char lastChar = str.charAt(str.length() - 1);
    int cut = Character.isSurrogate(lastChar) ? 2 : 1;
    return str.substring(0, str.length() - cut);
}

Why not use the escape sequence ... !为什么不使用转义序列...!

System.out.println(str + '\b');

Life is much easier now .现在生活轻松多了。 XD ! XD! ~ A readable one-liner ~ 可读的单行

Java 8爪哇 8

import java.util.Optional;

public class Test
{
  public static void main(String[] args) throws InterruptedException
  {
    System.out.println(removeLastChar("test-abc"));
  }

  public static String removeLastChar(String s) {
    return Optional.ofNullable(s)
      .filter(str -> str.length() != 0)
      .map(str -> str.substring(0, str.length() - 1))
      .orElse(s);
    }
}

Output : test-ab输出:测试-ab

public String removeLastCharacter(String str){
       String result = null;
        if ((str != null) && (str.length() > 0)) {
          return str.substring(0, str.length() - 1);
        }
        else{
            return "";
        }

}

if we want to remove file extension of the given file,如果我们想删除给定文件的文件扩展名,

** Sample code ** 示例代码

 public static String removeNCharactersFromLast(String str,int n){
    if (str != null && (str.length() > 0)) {
        return str.substring(0, str.length() - n);
    }

    return "";

}

if you have special character like ;如果您有特殊字符,例如 ; in json just use String.replace(";", "") otherwise you must rewrite all character in string minus the last.在 json 中只使用 String.replace(";", "") 否则你必须重写字符串中的所有字符减去最后一个。

I had to write code for a similar problem.我不得不为类似的问题编写代码。 One way that I was able to solve it used a recursive method of coding.我能够解决它的一种方法是使用递归编码方法。

static String removeChar(String word, char charToRemove)
{
    for(int i = 0; i < word.lenght(); i++)
    {
        if(word.charAt(i) == charToRemove)
        {
            String newWord = word.substring(0, i) + word.substring(i + 1);
            return removeChar(newWord, charToRemove);
        }
    }

    return word;
}

Most of the code I've seen on this topic doesn't use recursion so hopefully I can help you or someone who has the same problem.我在这个主题上看到的大多数代码都不使用递归,所以希望我可以帮助你或有同样问题的人。

How to make the char in the recursion at the end:如何在最后的递归中制作字符:

public static String  removeChar(String word, char charToRemove)
    {
        String char_toremove=Character.toString(charToRemove);
        for(int i = 0; i < word.length(); i++)
        {
            if(word.charAt(i) == charToRemove)
            {
                String newWord = word.substring(0, i) + word.substring(i + 1);
                return removeChar(newWord,charToRemove);
            }
        }
        System.out.println(word);
        return word;
    }

for exemple:举个例子:

removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"
removeChar("you should not go",'o') → "yu shuld nt goooo"

Here's an answer that works with codepoints outside of the Basic Multilingual Plane (Java 8+).这是一个适用于基本多语言平面(Java 8+)之外的代码点的答案。

Using streams:使用流:

public String method(String str) {
    return str.codePoints()
            .limit(str.codePoints().count() - 1)
            .mapToObj(i->new String(Character.toChars(i)))
            .collect(Collectors.joining());
}

More efficient maybe:可能更有效:

public String method(String str) {
    return str.isEmpty()? "": str.substring(0, str.length() - Character.charCount(str.codePointBefore(str.length())));
}

We can use substring.我们可以使用子字符串。 Here's the example,这是例子,

public class RemoveStringChar 
{
    public static void main(String[] args) 
    {   
        String strGiven = "Java";
        System.out.println("Before removing string character - " + strGiven);
        System.out.println("After removing string character - " + removeCharacter(strGiven, 3));
    }

    public static String removeCharacter(String strRemove, int position)
    {   
        return strRemove.substring(0, position) + strRemove.substring(position + 1);    
    }
}

just replace the condition of "if" like this:只需像这样替换“if”的条件:

if(a.substring(a.length()-1).equals("x"))'

this will do the trick for you.这将为您解决问题。

Suppose total length of my string=24 I want to cut last character after position 14 to end, mean I want starting 14 to be there.假设我的字符串的总长度 = 24 我想将位置 14 之后的最后一个字符剪切到结尾,这意味着我希望从 14 开始。 So I apply following solution.所以我应用以下解决方案。

String date = "2019-07-31T22:00:00.000Z";
String result = date.substring(0, date.length() - 14);

Easy Peasy:十分简单:

StringBuilder sb= new StringBuilder();
for(Entry<String,String> entry : map.entrySet()) {
        sb.append(entry.getKey() + "_" + entry.getValue() + "|");
}
String requiredString = sb.substring(0, sb.length() - 1);

For kotlin check out对于 kotlin 签出

    val string = "<<<First Grade>>>"
    println(string.drop(6)) // st Grade>>>
    println(string.dropLast(6)) // <<<First Gr
    println(string.dropWhile { !it.isLetter() }) // First Grade>>>
    println(string.dropLastWhile { !it.isLetter() }) // <<<First Grade

如果要在最后删除特定字符,可以使用:

myString.removeSuffix("x")

Simple Kotlin way:简单的Kotlin方式:

if (inputString.isNotEmpty()) {
    inputString.dropLast(1) // You can define how many chars you want to remove
}

Refer to the official doc here请参阅此处的官方文档

This is the one way to remove the last character in the string: 这是删除字符串中最后一个字符的一种方法:

Scanner in = new Scanner(System.in);
String s = in.nextLine();
char array[] = s.toCharArray();
int l = array.length;
for (int i = 0; i < l-1; i++) {
    System.out.print(array[i]);
}

Use StringUtils.Chop(Str) it also takes care of null and empty strings, u need to import common-io:使用 StringUtils.Chop(Str) 它还处理空字符串和空字符串,您需要导入 common-io:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.8.0</version>
    </dependency>

你可以做到hereString = hereString.replace(hereString.chatAt(hereString.length()-1),'whitespeace');

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

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