java常见字符串操作
内容摘要
一、使用length()方法获取字符串的长度public class maintest {
public static void main(String[] args) {
String str = "abcdefg";
//length():统
public static void main(String[] args) {
String str = "abcdefg";
//length():统
文章正文
一、使用length()方法获取字符串的长度
1 2 3 4 5 6 7 8 | public class maintest { public static void main(String[] args) { String str = "abcdefg" ; //length():统计当前字符串的字符个数 int i = str.length(); System.out.println(i); } } |
二、使用indexOf()方法查找指定字符再字符串中的位置
1 2 3 4 5 6 7 8 | public class maintest { public static void main(String[] args) { String str = "abcdefg" ; //indexOf():查找指定字符再字符串中的位置 int index = str.indexOf( "a" ); System.out.println(index); } } |
三、使用toUpperCase()方法将字符串中的字符变为了大写形式
1 2 3 4 5 6 7 8 9 | public class maintest { public static void main(String[] args) { String str = "abcdefg" ; //小写转大写 //toUpperCase():将字符串中的字符变为了大写形式 String str = str.toUpperCase(); System.out.println(str); } } |
四、使用toLowerCase()方法将字符串中的字符变为小写
1 2 3 4 5 6 7 8 | public class maintest { public static void main(String[] args) { //toLowerCase():将字符串中的字符变为小写 String str = "WWMMDDHH" ; String str1 = str3.toLowerCase(); System.out.println(str); } } |
五、使用substring()方法截取字符串
1 2 3 4 5 6 7 8 9 10 11 | public class maintest { public static void main(String[] args) { String str = "abcdefg" ; //substring:截取字符串 String str = "abcdefg" ; String str = str5.substring(0, 3); System.out.println(str); String str = str5.substring(3); System.out.println(str); } } |
六、使用replaceAll()方法替换当前字符串中指定内容
1 2 3 4 5 6 7 | public class maintest { public static void main(String[] args) { String str = "abcdefg" ; String str = str5.replaceAll( "abc" , "xyz" ); System.out.println(str); } } |
七、使用trim()方法能够去掉当前字符串中两端的空格
1 2 3 4 5 6 7 8 9 | public class maintest { public static void main(String[] args) { String str = " abc def " ; System.out.println(str.length()); String str1 = str9.trim(); System.out.println(str); System.out.println(str1); } } |
八、字符串+字符串 等于拼接
1 2 3 4 5 6 7 | public class maintest { public static void main(String[] args) { String str1 = "123" ; String str2 = "100" ; System.out.println(str1+str2); } } |
九、将字符串变为整数
1 2 3 4 5 6 7 8 9 | public class maintest { public static void main(String[] args) { String str1 = "123" ; String str2 = "100" ; int num1 = Integer.parseInt(str1); int num2 = Integer.parseInt(str2); System.out.println(num1+num2); } } |
十、使用charAt()找到指定字符串中位置的字符
1 2 3 4 5 6 7 8 | public class maintest { public static void main(String[] args) { String str1000 = "abcde" ; //charAt:找到指定字符串中位置的字符 char char = str1000.charAt(2); System.out.println(char); } } |
代码注释
[!--zhushi--]