java中如何去掉最后一个指定字符
时间: 2023-09-01 10:08:04 浏览: 163
您可以使用Java中的`substring`方法和`lastIndexOf`方法来去掉字符串中的最后一个指定字符。以下是一个示例代码:
```java
public class RemoveLastCharExample {
public static void main(String[] args) {
String str = "Hello, world!";
char ch = '!';
int lastIndex = str.lastIndexOf(ch);
if (lastIndex != -1) { // 如果字符串中存在指定字符
str = str.substring(0, lastIndex) + str.substring(lastIndex + 1);
}
System.out.println(str);
}
}
```
在上面的代码中,我们定义了一个字符串`str`和一个指定字符`ch`。使用`lastIndexOf`方法查找字符串中最后一个指定字符的位置,如果找到了指定字符,则使用`substring`方法从字符串中去掉最后一个指定字符。最后输出处理后的字符串。
如果字符串中不存在指定字符,则`lastIndexOf`方法返回-1,此时不需要进行任何处理。
相关问题
java怎么去掉最后两位指定字符串
你可以使用 String 类的 substring() 方法和 concat() 方法来去掉最后两位指定字符串。具体来说,可以使用 substring() 方法获取原字符串除去最后两位后的子字符串,然后使用 concat() 方法将其与指定字符串拼接起来。以下是一个示例代码:
```
String str = "Hello World!";
String suffix = "ld";
String result = str.substring(0, str.length() - 2).concat(suffix);
System.out.println(result);
```
在这个例子中,我们首先定义了一个字符串 `str` 和一个后缀字符串 `suffix`,然后使用 `substring()` 方法来获取原字符串除去最后两位后的子字符串。具体来说,我们使用 `str.length()` 来获取字符串的长度,然后减去 2,得到最后两位的位置。最后,我们将这个位置传递给 `substring()` 方法,以获取截取后的字符串。接着,我们使用 `concat()` 方法将截取后的字符串与后缀字符串拼接起来,得到最终的字符串 `result`。
java实现去掉字符串中指定的字符(附完整源码)
以下是Java实现去掉字符串中指定的字符的完整源码:
```java
public class RemoveChar {
public static void main(String[] args) {
String input = "Hello, World!";
char charToRemove = 'o';
String output = removeChar(input, charToRemove);
System.out.println(output);
}
public static String removeChar(String input, char charToRemove) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c != charToRemove) {
output.append(c);
}
}
return output.toString();
}
}
```
在这个程序中,我们首先定义一个字符串input和一个要去除的字符charToRemove。然后,我们调用removeChar方法去掉字符串中指定的字符,并将结果输出。
在removeChar方法中,我们使用StringBuilder类创建一个空的字符串output,然后遍历输入字符串input中的每个字符。如果当前字符不是要去除的字符charToRemove,我们将它添加到output字符串中。最后,我们返回output字符串。
需要注意的是,如果要去除的字符可能在字符串中出现多次,可以使用replace方法对输入字符串进行替换。