Java函数使用示例-10个常用函数案例
1. indexOf()函数
这个函数用于定位一个给定字符或字符串在一个字符串内的位置。比如:
String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index);
输出结果为:7
2. replace()函数
这个函数用于将字符串内的某个字符或字符串替换成另一个字符或字符串。比如:
String str = "Hello, world!";
String newStr = str.replace("world", "Java");
System.out.println(newStr);
输出结果为:Hello, Java!
3. trim()函数
这个函数用于去除字符串前后的空格。比如:
String str = " Hello, world! ";
String newStr = str.trim();
System.out.println(newStr);
输出结果为:Hello, world!
4. toUpperCase()函数
这个函数用于将字符串中的所有字母转换成大写字母。比如:
String str = "Hello, world!";
String newStr = str.toUpperCase();
System.out.println(newStr);
输出结果为:HELLO, WORLD!
5. toLowerCase()函数
这个函数用于将字符串中的所有字母转换成小写字母。比如:
String str = "Hello, world!";
String newStr = str.toLowerCase();
System.out.println(newStr);
输出结果为:hello, world!
6. substring()函数
这个函数用于截取字符串的一部分。比如:
String str = "Hello, world!";
String newStr = str.substring(0, 5);
System.out.println(newStr);
输出结果为:Hello
7. valueOf()函数
这个函数用于将基本类型的数据转换成字符串。比如:
int num = 123;
String str = String.valueOf(num);
System.out.println(str);
输出结果为:123
8. equals()函数
这个函数用于判断两个字符串是否相等。比如:
String str1 = "Hello, world!";
String str2 = "Hello, Java!";
boolean result1 = str1.equals(str2);
boolean result2 = str1.equals("Hello, world!");
System.out.println(result1);
System.out.println(result2);
输出结果为:false true
9. split()函数
这个函数用于将一个字符串按照指定的分隔符分割成字符串数组。比如:
String str = "Hello,Java,world";
String[] arr = str.split(",");
for(String s:arr){
System.out.println(s);
}
输出结果为:
Hello
Java
world
10. length()函数
这个函数用于获取一个字符串的长度。比如:
String str = "Hello, world!";
int len = str.length();
System.out.println(len);
输出结果为:13
以上是Java中10个常用的字符串函数,可以帮助读者更好地处理字符串相关的问题。
