10个常用的Java函数示例演示
1. String.substring()
该函数允许从一个字符串中截取一个子串。参数为起始位置和结束位置,返回的是一个新的字符串。例如:
String str = "Hello World";
String newStr = str.substring(0, 5);
System.out.println(newStr);
输出结果为:Hello。
2. Arrays.sort()
该函数用于对数组进行排序,可接受任何类型的数组作为参数。例如:
int[] arr = {3, 8, 1, 7, 2};
Arrays.sort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
输出结果为:1 2 3 7 8。
3. Math.pow()
该函数用于计算某个数的幂,接收两个参数, 个为底数,第二个为指数。例如:
double result = Math.pow(2, 3);
System.out.println(result);
输出结果为:8.0。
4. String.indexOf()
该函数用于查找某个字符串在另一个字符串中的位置,如果找到了就返回位置,否则返回-1。例如:
String str = "Hello World";
int pos = str.indexOf("World");
System.out.println(pos);
输出结果为:6。
5. Integer.parseInt()
该函数用于将一个字符串转换为int类型的数字。例如:
String str = "123";
int num = Integer.parseInt(str);
System.out.println(num);
输出结果为:123。
6. String.split()
该函数用于将一个字符串根据某种分隔符分割为多个字符串。例如:
String str = "hello,world";
String[] arr = str.split(",");
for (String s : arr) {
System.out.println(s);
}
输出结果为:
hello
world
7. String.replace()
该函数用于将一个字符串中某个字符或字符串替换为另一个字符或字符串。例如:
String str = "hello world";
String newStr = str.replace("world", "Java");
System.out.println(newStr);
输出结果为:hello Java。
8. String.toLowerCase()
该函数用于将一个字符串中所有的大写字母转换为小写字母。例如:
String str = "Hello World";
String newStr = str.toLowerCase();
System.out.println(newStr);
输出结果为:hello world。
9. Double.parseDouble()
该函数用于将一个字符串转换为double类型的数字。例如:
String str = "3.14";
double num = Double.parseDouble(str);
System.out.println(num);
输出结果为:3.14。
10. String.trim()
该函数用于去除一个字符串两端的空格。例如:
String str = " Hello World ";
String newStr = str.trim();
System.out.println(newStr);
输出结果为:Hello World。
