动手实践:10个常用的Java函数
Java是一到广泛使用的编程语言,它具有强大的优势和功能。其中最常用的是一些函数,这些函数通常具有简明的语法和高效的功能,使Java开发人员可以更快地开发出优秀的程序。下面是十个常用的Java函数:
1. equals()
该函数用于比较两个对象是否相等。如果两个对象相等,返回true;否则返回false。
例子:
String str1 = "Hello";
String str2 = "Hello";
boolean result = str1.equals(str2);
System.out.println(result); // 输出 true
2. length()
该函数用于获取字符串的长度,返回值是一个整数。
例子:
String str = " Hello World! ";
int len = str.length();
System.out.println(len); // 输出 13
3. substring()
该函数用于从一个字符串中截取子串。
例子:
String str = "Hello World";
String substr = str.substring(2, 5); // 包含2,不包含5
System.out.println(substr); // 输出 llo
4. toLowerCase() 和 toUpperCase()
这两个函数分别用于将字符串转换为小写和大写字母。
例子:
String str = "Hello World!";
String lowerStr = str.toLowerCase();
String upperStr = str.toUpperCase();
System.out.println(lowerStr); // 输出 hello world!
System.out.println(upperStr); // 输出 HELLO WORLD!
5. trim()
该函数用于去除字符串两端的空白符,返回一个新的字符串。
例子:
String str = " Hello World! ";
String trimStr = str.trim();
System.out.println(trimStr); // 输出 Hello World!
6. charAt()
该函数用于获取指定位置的字符。
例子:
String str = "Hello World!";
char ch = str.charAt(4);
System.out.println(ch); // 输出 o
7. indexOf() 和 lastIndexOf()
这两个函数分别用于在字符串中查找某个子串的位置,返回一个整数。
例子:
String str = "Hello World!";
int index = str.indexOf("o");
int lastIndex = str.lastIndexOf("o");
System.out.println(index); // 输出 4
System.out.println(lastIndex); // 输出 7
8. split()
该函数用于将字符串按照指定的字符分割成多个子串,返回一个字符串数组。
例子:
String str = "Apple,Banana,Orange";
String[] arr = str.split(",");
for (String s : arr) {
System.out.println(s);
}
// 输出 Apple
// 输出 Banana
// 输出 Orange
9. replace()
该函数用于将字符串中的某个字符或者字符串替换成指定的新字符或字符串。
例子:
String str = "Hello World!";
String newStr = str.replace("o", "*");
System.out.println(newStr); // 输出 Hell* W*rld!
10. parseInt()
该函数用于将一个字符串解析成一个整数。
例子:
String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // 输出 123
以上是Java常用的十个函数,简单易用。可以帮助Java开发人员更快地解决问题,提高开发效率。
