小编给大家分享一下java常见的字符串操作方法示例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

一、使用length()方法获取字符串的长度
public class maintest {
public static void main(String[] args) {
String str = "abcdefg";
//length():统计当前字符串的字符个数
int i = str.length();
System.out.println(i);
}
}
二、使用indexOf()方法查找指定字符再字符串中的位置
public class maintest {
public static void main(String[] args) {
String str = "abcdefg";
//indexOf():查找指定字符再字符串中的位置
int index = str.indexOf("a");
System.out.println(index);
}
}
三、使用toUpperCase()方法将字符串中的字符变为了大写形式
public class maintest {
public static void main(String[] args) {
String str = "abcdefg";
//小写转大写
//toUpperCase():将字符串中的字符变为了大写形式
String str = str.toUpperCase();
System.out.println(str);
}
}
四、使用toLowerCase()方法将字符串中的字符变为小写
public class maintest {
public static void main(String[] args) {
//toLowerCase():将字符串中的字符变为小写
String str = "WWMMDDHH";
String str1 = str3.toLowerCase();
System.out.println(str);
}
}
五、使用substring()方法截取字符串
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()方法替换当前字符串中指定内容
public class maintest {
public static void main(String[] args) {
String str = "abcdefg";
String str = str5.replaceAll("abc", "xyz");
System.out.println(str);
}
}
七、使用trim()方法能够去掉当前字符串中两端的空格
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);
}
}
八、字符串+字符串 等于拼接
public class maintest {
public static void main(String[] args) {
String str1 = "123";
String str2 = "100";
System.out.println(str1+str2);
}
}
九、将字符串变为整数
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()找到指定字符串中位置的字符
public class maintest {
public static void main(String[] args) {
String str1000 = "abcde";
//charAt:找到指定字符串中位置的字符
char char = str1000.charAt(2);
System.out.println(char);
}
}
以上是java常见的字符串操作方法示例的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联成都网站设计公司行业资讯频道!
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。