欢迎访问宙启技术站
智能推送

Java字符串函数:掌握字符串常用的函数和操作方法

发布时间:2023-05-28 23:42:28

Java语言中字符串操作是常见的操作之一,字符串中常用的函数和操作方法有很多。本文将介绍Java字符串常用的函数和操作方法,帮助初学者快速掌握字符串的操作方法。

一、字符串创建

Java中创建字符串有三种方式:使用双引号创建、使用构造函数创建和使用字符串连接符创建。

1.使用双引号创建

使用双引号创建字符串,这是最常见的创建字符串的方法。如:

String str = "Hello World!";

2.使用构造函数创建

使用构造函数创建字符串,即创建一个新的String对象。如:

String str = new String("Hello World!");

3.使用字符串连接符创建

使用字符串连接符“+”创建字符串,即将两个字符串连接到一起。如:

String str1 = "Hello";

String str2 = "World";

String str = str1 + " " + str2 + "!";

二、字符串的常用方法

1.字符串截取方法

字符串截取是常用的字符串操作之一,Java中字符串截取方法是通过indexOf()和substring()方法实现的。indexOf()方法返回字符串中子串所在的位置,substring()方法根据位置截取子串。

例如:

String str = "Hello World!";

int index = str.indexOf("W");//返回字母W所在位置

String subStr = str.substring(index);//从index位置开始截取子串

System.out.println(subStr);//输出World!

2.字符串比较方法

Java中字符串比较方法有两种,equals()方法和compareTo()方法。equals()方法用于比较两个字符串是否相等,compareTo()方法用于比较两个字符串的大小关系。

例如:

String str1 = "Hello";

String str2 = "World";

if(str1.equals(str2)){

    System.out.println("两个字符串相等");

}else{

    System.out.println("两个字符串不相等");

}

int result = str1.compareTo(str2);

if(result == 0){

    System.out.println("两个字符串相等");

}else if(result > 0){

    System.out.println("str1大于str2");

}else{

    System.out.println("str1小于str2");

}

3.字符串替换方法

Java中字符串替换方法是replace()方法,该方法用于将字符串中指定的字符替换成别的字符。

例如:

String str = "Hello World!";

String newStr = str.replace("o", "0");//将字母o替换成数字0

System.out.println(newStr);//输出Hell0 W0rld!

4.字符串大小写转换方法

Java中字符串大小写转换方法有三种:toUpperCase()、toLowerCase()和toUpperCase(Locale locale)。

例如:

String str = "Hello World!";

String upperStr = str.toUpperCase();//将字符串转换成大写

System.out.println(upperStr);//输出HELLO WORLD!

String lowerStr = str.toLowerCase();//将字符串转换成小写

System.out.println(lowerStr);//输出hello world!

String upFirst = str.substring(0,1).toUpperCase()+str.substring(1);//将字符串的首字母转换成大写

System.out.println(upFirst);//输出Hello World!

5.字符串分割方法

Java中字符串分割方法是split()方法,该方法用于将字符串根据指定的分隔符分割成一个字符串数组。

例如:

String str = "Tom,Cat,Dog";

String[] arr = str.split(",");//将字符串以逗号为分隔符分割成字符串数组

for(String s : arr){

    System.out.println(s);//输出Tom Cat Dog

}

6.字符串去除空格方法

Java中字符串去除空格方法有两种:trim()和replaceAll("\\s*", ""),前者只能去掉首尾的空格,后者可以去掉字符串中所有的空格。

例如:

String str = "  Hello World!  ";

System.out.println(str.trim());//输出Hello World!

System.out.println(str.replaceAll("\\s*", ""));//输出HelloWorld!

三、字符串不可变性

在Java中,字符串是不可变的,这意味着一旦创建了一个字符串对象,就不能改变它的内容。例如:

String str = "Hello";

str.concat(" World!");//该方法返回一个新字符串,但并没有改变原字符串的内容

System.out.println(str);//输出Hello,而不是Hello World!

总之,字符串在Java中是非常常见的数据类型,学习字符串的操作方法对于开发Java程序非常重要。本文介绍了Java字符串的创建、常用方法、不可变性等方面的知识,给初学者提供了一些基础指导。同时,也需要注意字符串的空间占用和效率问题,避免过度使用字符串操作带来的性能损耗。