java 字符串移除最后一位
时间: 2023-04-01 14:04:33 浏览: 72
可以使用 String 类的 substring() 方法,将字符串的最后一位移除。
例如:
String str = "Hello World!";
String newStr = str.substring(, str.length()-1);
System.out.println(newStr);
输出结果为:
Hello World
相关问题
java 字符串移除后四位
您好,可以使用 Java 的 substring() 方法来移除字符串的后四位。具体代码如下:
String str = "这是一个字符串";
String newStr = str.substring(, str.length() - 4);
这样就可以得到移除后四位的新字符串了。
用Java写无重复字符串的最长子串并注释
以下是用Java写无重复字符串的最长子串并注释的代码:
```java
import java.util.HashSet;
public class LongestSubstringWithoutRepeatingCharacters {
public static int lengthOfLongestSubstring(String s) {
int n = s.length();
int ans = 0;
HashSet<Character> set = new HashSet<>();
int i = 0, j = 0;
while (i < n && j < n) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
} else {
set.remove(s.charAt(i++));
}
}
return ans;
}
public static void main(String[] args) {
String s = "abcabcbb";
int length = lengthOfLongestSubstring(s);
System.out.println("The length of the longest substring without repeating characters is: " + length);
}
}
```
注释如下:
1. `import java.util.HashSet;` 导入 HashSet 类。
2. `public class LongestSubstringWithoutRepeatingCharacters {` 定义一个名为 LongestSubstringWithoutRepeatingCharacters 的类。
3. `public static int lengthOfLongestSubstring(String s) {` 定义一个名为 lengthOfLongestSubstring 的静态方法,它接受一个字符串 s 作为参数,返回一个整数。
4. `int n = s.length();` 获取字符串 s 的长度。
5. `int ans = 0;` 定义一个变量 ans,用于存储最长子串的长度。
6. `HashSet<Character> set = new HashSet<>();` 创建一个 HashSet 对象 set,用于存储不重复的字符。
7. `int i = 0, j = 0;` 定义两个指针 i 和 j,分别指向子串的起始位置和结束位置。
8. `while (i < n && j < n) {` 循环遍历字符串 s,直到 i 或 j 超出字符串的范围。
9. `if (!set.contains(s.charAt(j))) {` 如果 set 中不包含 s.charAt(j) 这个字符。
10. `set.add(s.charAt(j++));` 将 s.charAt(j) 添加到 set 中,并将 j 向右移动一位。
11. `ans = Math.max(ans, j - i);` 更新最长子串的长度。
12. `} else {` 如果 set 中已经包含 s.charAt(j) 这个字符。
13. `set.remove(s.charAt(i++));` 将 s.charAt(i) 从 set 中移除,并将 i 向右移动一位。
14. `}` 结束 if-else 语句。
15. `}` 结束 while 循环。
16. `return ans;` 返回最长子串的长度。
17. `public static void main(String[] args) {` 定义一个名为 main 的静态方法,它接受一个字符串数组 args 作为参数。
18. `String s = "abcabcbb";` 定义一个字符串 s。
19. `int length = lengthOfLongestSubstring(s);` 调用 lengthOfLongestSubstring 方法,获取最长子串的长度。
20. `System.out.println("The length of the longest substring without repeating characters is: " + length);` 输出最长子串的长度。