Java字符串函数的实用例子
发布时间:2023-07-01 14:15:30
Java字符串函数是用于处理字符串的一系列方法,下面是一些实用的例子:
1. length()函数:用于获取字符串的长度。例如:
String str = "Hello World";
int len = str.length();
System.out.println("字符串的长度为:" + len);
2. charAt()函数:用于返回指定索引位置的字符。索引从0开始。例如:
String str = "Hello World";
char ch = str.charAt(0);
System.out.println("字符串的 个字符为:" + ch);
3. substring()函数:用于返回指定索引范围内的子字符串。例如:
String str = "Hello World";
String sub = str.substring(6, 11);
System.out.println("字符串的子串为:" + sub);
4. toUpperCase()和toLowerCase()函数:用于将字符串转换为全大写或全小写。例如:
String str = "Hello World";
String upper = str.toUpperCase();
String lower = str.toLowerCase();
System.out.println("全大写字符串:" + upper);
System.out.println("全小写字符串:" + lower);
5. equals()函数:用于判断两个字符串是否相等。例如:
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2);
System.out.println("字符串相等:" + isEqual);
6. startsWith()和endsWith()函数:用于判断字符串是否以指定的前缀或后缀开头/结尾。例如:
String str = "Hello World";
boolean startsWith = str.startsWith("Hello");
boolean endsWith = str.endsWith("World");
System.out.println("字符串以Hello开头:" + startsWith);
System.out.println("字符串以World结尾:" + endsWith);
7. contains()函数:用于判断字符串是否包含指定的子串。例如:
String str = "Hello World";
boolean contains = str.contains("o W");
System.out.println("字符串包含o W子串:" + contains);
8. indexOf()和lastIndexOf()函数:用于返回指定字符或子串在字符串中 次或最后一次出现的索引位置。例如:
String str = "Hello World";
int index1 = str.indexOf("o");
int index2 = str.lastIndexOf("o");
System.out.println("字符串中 个o的索引位置:" + index1);
System.out.println("字符串中最后一个o的索引位置:" + index2);
9. replaceAll()函数:用于将字符串中的所有匹配子串替换为指定的新子串。例如:
String str = "Hello World";
String replaced = str.replaceAll("o", "e");
System.out.println("替换后的字符串:" + replaced);
10. split()函数:用于将字符串按照指定的分隔符切分成多个子串,并返回一个字符串数组。例如:
String str = "Hello,World";
String[] split = str.split(",");
System.out.println("切分后的字符串数组:" + Arrays.toString(split));
这些例子展示了Java字符串函数的一些常见用法,可以根据实际需求灵活运用这些函数来处理字符串。
