我是靠谱客的博主 无心凉面,这篇文章主要介绍java常见字符串操作,现在分享给大家,希望可以做个参考。

Java String 类 字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。今天就为大家介绍一下java常见的字符串操作方法。

一、使用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); } }
登录后复制

以上就是我为大家总结的始终java常用的字符串操作。如果想了解更多关于java的知识大家可以点击:java教程

以上就是java常见字符串操作的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是无心凉面最近收集整理的关于java常见字符串操作的全部内容,更多相关java常见字符串操作内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(103)

评论列表共有 0 条评论

立即
投稿
返回
顶部