简体   繁体   中英

Delete Last and First Char in a String

I just wanted to ask how to remove the first and the last char form a String. The easiest and best looking would be great :)

String s = "Hello World!";
s = s.substring(1, s.length() - 1); // --> "ello World"

Use the substring() method:

String newString = oldString.substring(1, oldString.length() -1);

This skips the first char and substrings down to the end minus 1.

You can take advatage of String.substring() method:

public String removeFirstAndLastChar(String s)
{
   String withoutFirstChar = s.substring(1);

   return withoutFirstChar.substring(withoutFirstChar.length() - 1);
}

or shorter way:

public String removeFirstAndLastChar(String s)
{
   return s.substring(1, s.length() - 1);
}

您可能想使用String.substring()

Read about text functions:

substring(int start, int end);
length();

Here http://developer.android.com/reference/java/lang/String.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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