删除String的最后一个 并返回 三种方法
时间: 2024-05-07 22:21:40 浏览: 10
方法一:使用substring()方法
```
String str = "Hello World!";
str = str.substring(0, str.length()-1);
```
方法二:使用StringBuilder的deleteCharAt()方法
```
StringBuilder str = new StringBuilder("Hello World!");
str.deleteCharAt(str.length()-1);
```
方法三:使用StringBuffer的deleteCharAt()方法
```
StringBuffer str = new StringBuffer("Hello World!");
str.deleteCharAt(str.length()-1);
```
这三种方法都可以删除String的最后一个字符并返回删除后的结果。其中,使用substring()方法需要重新赋值给原来的字符串变量,而使用StringBuilder和StringBuffer则可以直接在原来的对象上进行修改。
相关问题
删除String的最后一个
可以使用以下代码删除字符串的最后一个字符:
```java
String str = "example";
str = str.substring(0, str.length() - 1);
System.out.println(str); // 输出 "exampl"
```
`substring()` 方法的参数为起始位置和结束位置(不包含),因此将起始位置设置为0,结束位置设置为字符串长度减1,即可得到一个新的字符串,该字符串去掉了最后一个字符。注意,这个方法不会改变原始的字符串,而是返回一个新的字符串。
c# string 替换最后一个字符为其他字符
可以使用 `Substring()` 和 `Remove()` 方法来实现替换最后一个字符。具体步骤如下:
1. 首先判断字符串是否为空或者长度是否为0,如果是,则不进行操作,直接返回原字符串。
2. 使用 `Substring()` 方法获取字符串中除最后一个字符外的所有字符。
3. 使用 `Remove()` 方法删除字符串中最后一个字符。
4. 将要替换的字符添加到字符串的末尾。
5. 将第2步和第4步得到的字符串进行拼接并返回。
以下是示例代码:
```csharp
public static string ReplaceLastCharacter(string source, char newChar)
{
if (string.IsNullOrEmpty(source))
{
return source;
}
string substring = source.Substring(0, source.Length - 1);
string replacedString = substring.Remove(substring.Length - 1) + newChar;
return replacedString;
}
```
可以调用这个方法来替换字符串的最后一个字符。例如:
```csharp
string originalString = "abcde";
char newChar = 'f';
string replacedString = ReplaceLastCharacter(originalString, newChar);
Console.WriteLine(replacedString); // 输出 "abcdf"
```