文章目录
String字符串 和 整型int 的相互转换
String转化为int
俩种方法
- Integer.parseInt(str)
- Integer.valueOf(str).intValue()
注意:Integer是int的包装类
Java内置包装类
代码演示:
public class Main {
public static void main(String[] args) {
String str = "123";
int n = 0;
// 第一种转换方法:Integer.parseInt(str)
n = Integer.parseInt(str);
System.out.println("Integer.parseInt(str) : " + n);
// 第二种转换方法:Integer.valueOf(str).intValue()
n = 0;
n = Integer.valueOf(str).intValue();
System.out.println("Integer.parseInt(str) : " + n);
}
}
Integer.parseInt(str) : 123
Integer.parseInt(str) : 123
注意事项:在 String 转换为 int 时,String 的值一定是整数,否则会报数字转换异常(java.lang.NumberFormatException)。
int 转换为 String
整型 int 转 String 字符串类型有以下 3 种方法:
- String s = String.valueOf(i);
- String s = Integer.toString(i);
- String s = “” + i;
代码演示:
public class Main {
public static void main(String[] args) {
int num = 10;
// 第一种方法:String.valueOf(i);
num = 10;
String str1 = String.valueOf(num);
System.out.println("str1:" + str1);
// 第二种方法:Integer.toString(i);
num = 10;
String str2 = Integer.toString(num);
System.out.println("str2:" + str2);
// 第三种方法:"" + i;
String str3 = num + "";
System.out.println("str3:" + str3);
}
}
str1:10
str2:10
str3:10
注意事项:第三种方式相对前俩种耗时较长。在第一种 valueOf() 方法时,注意 valueOf 括号中的值不能为空,否则会报空指针异常(NullPointerException)。
字符串拼接
使用连接运算符 “+”
与绝大多数的程序设计语言一样,Java 语言允许使用“+”号连接(拼接)两个字符串。“+”运算符是最简单、最快捷,也是使用最多的字符串连接方式。在使用“+”运算符连接字符串和 int 型(或 double 型)数据时,“+”将 int(或 double)型数据自动转换成 String 类型。
代码演示:
public static void main(String[] args) {
int[] no = new int[] {
501, 101, 204, 102, 334 }; // 定义学号数组
String[] names = new String[] {
"张城", "刘丽丽", "李国旺", "孟红霞", "贺宁" }; // 定义姓名数组
String[] classes = new String[] {
"数学", "语文", "数学", "英语", "英语" }; // 定义课程数组
System.out.println("本次考试学生信息如下:");
// 循环遍历数组,连接字符串
for (int i = 0; i < no.length; i++) {
System.out.println("学号:" + no[i] + "|姓名:" + names[i] + "|课程:" + classes[i] + "|班级:" + "初二(三)班");
}
}
本次考试学生信息如下:
学号:501|姓名:张城|课程:数学|班级:初二(三)班
学号:101|姓名:刘丽丽|课程:语文|班级:初二(三)班
学号:204|姓名:李国旺|课程:数学|班级:初二(三)班
学号:102|姓名:孟红霞|课程:英语|班级:初二(三)班
学号:334|姓名:贺宁|课程:英语|班级:初二(三)班
使用 concat() 方法
如 concat() 方法的语法所示,concat() 方法一次只能连接两个字符串,如果需要连接多个字符串,需要调用多次 concat() 方法。
代码演示:
public class Main {
public static void main(String[] args) {
String info = "三国演义、";
info = info.concat("西游记、");
info = info.concat("水浒传、");
info = info.concat("红楼梦");
System.out.println(info);
String cn = "中国";
System.out.println(cn.concat("北京").concat("海淀区").concat("人民公园"));
}
}
三国演义、西游记、水浒传、红楼梦
中国北京海淀区人民公园
连接其他类型数据
字符串与字符串进行连接,字符串也可同其他基本数据类型进行连接。
如果将字符串同这些数据类型数据进行连接,此时会将这些数据直接转换成字符串。
编写一个 Java 程序,实现将字符串与整型、浮点型变量相连并输出结果。
代码演示如下:
public static void main(String[] args) {
String book = "三国演义"; // 字符串
int price = 59; // 整型变量
float readtime = 2.5f; // 浮点型变量
System.out.println("我买了一本图书,名字是:" + book + "\n价格是:" + price + "\n我每天阅读" + readtime + "小时");
}
我买了一本图书,名字是:三国演义
价格是:59
我每天阅读2.5小时
注意:只要“+”运算符的一个操作数是字符串,编译器就会将另一个操作数转换成字符串形式,所以应该谨慎地将其他数据类型与字符串相连,以免出现意想不到的结果。
获取字符串长度
在 Java 中,要获取字符串的长度,可以使用 String 类的 length() 方法,其语法形式如下:
字符串名.length();
public class Main {
public static void main(String[] args) {
String string = "abc 123";
System.out.println("string的长度为:" + string.length());
}
}
string的长度为:7
字符串大小写转换
String 类的 toLowerCase() 方法可以将字符串中的所有字符全部转换成小写,而非字母的字符不受影响。语法格式如下:
字符串名.toLowerCase() // 将字符串中的字母全部转换为小写,非字母不受影响
toUpperCase() 则将字符串中的所有字符全部转换成大写,而非字母的字符不受影响。语法格式如下:
字符串名.toUpperCase() // 将字符串中的字母全部转换为大写,非字母不受影响
代码演示:
public class Main {
public static void main(String[] args) {
String string = "I am DongKaizi"; // 定义原始字符串
System.out.println("都大写:" + string.toUpperCase());
System.out.println("都小写:" + string.toLowerCase());
}
}
都大写:I AM DONGKAIZI
都小写:i am dongkaizi
去除字符串中的空格(trim())
trim() 方法的语法形式如下:
字符串名.trim()
public class Main {
public static void main(String[] args) {
String string = " I am DongKaizi "; // 定义原始字符串
System.out.println("原字符串长度为:" + string.length());
System.out.println("去除空格后的字符串为:" + string.trim().length());
}
}
原字符串长度为:16
去除空格后的字符串为:14
- 如果不确定要操作的字符串首尾是否有空格,最好在操作之前调用该字符串的 trim() 方法去除首尾空格,然后再对其进行操作。
- trim() 只能去掉字符串中前后的半角空格(英文空格),而无法去掉全角空格(中文空格)。
提取字符串
在 String 中提供了俩个截取字符串的方法,一个是从指定位置截取到字符串结尾,另一个是截取指定范围的内容。
substring(int beginIndex,int endIndex)
- 此方法中的 beginIndex 表示截取的起始索引,截取的字符串中包括起始索引对应的字符;
- endIndex 表示结束索引,截取的字符串中不包括结束索引对应的字符,如果不指定 endIndex,则表示截取到目标字符串末尾。
- 该方法用于提取位置 beginIndex 和位置 endIndex 位置之间的字符串部分。
注意:substring() 方法是按字符截取,而不是按字节截取。
public class Main {
public static void main(String[] args) {
String day = "Today is Monday"; //原始字符串
System.out.println("substring(0)结果:"+day.substring(0));
System.out.println("substring(2)结果:"+day.substring(2));
System.out.println("substring(10)结果:"+day.substring(10));
System.out.println("substring(2,10)结果:"+day.substring(2,10));
System.out.println("substring(0,5)结果:"+day.substring(0,5));
}
}
substring(0)结果:Today is Monday
substring(2)结果:day is Monday
substring(10)结果:onday
substring(2,10)结果:day is M
substring(0,5)结果:Today
分割字符串
String 类的 split() 方法可以按指定的分割符对目标字符串进行分割,分割后的内容存放在字符串数组中。
该方法主要有如下两种重载形式:
str.split(String sign)
str.split(String sign,int limit)
其中它们的含义如下:
- str 为需要分割的目标字符串。
- sign 为指定的分割符,可以是任意字符串。
- limit 表示分割后生成的字符串的限制个数,如果不指定,则表示不限制,直到将整个目标字符串完全分割为止。
使用分隔符注意如下:
- “.”和“|”都是转义字符,必须得加“\”。
- 如果用“.”作为分隔的话,必须写成String.split("\."),这样才能正确的分隔开,不能用String.split(".")。
- 如果用“|”作为分隔的话,必须写成String.split("\|"),这样才能正确的分隔开,不能用String.split("|")。
- 如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如:“acount=? and uu =? or n=?”,把三个都分隔出来,可以用String.split(“and|or”)。
代码演示:
public class Main {
public static void main(String[] args) {
String Colors = "Red,Black,White,Yellow,Blue";
String[] arr1 = Colors.split(","); // 不限制元素个数
String[] arr2 = Colors.split(",", 3); // 限制元素个数为3
System.out.println("所有颜色为:");
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}
System.out.println("前三个颜色为:");
for (int j = 0; j < arr2.length; j++) {
System.out.println(arr2[j]);
}
}
}
所有颜色为:
Red
Black
White
Yellow
Blue
前三个颜色为:
Red
Black
White,Yellow,Blue
注意:从输出的结果可以看出,当指定分割字符串后组成的数组长度(大于或等于 1)时,数组的前几个元素为字符串分割后的前几个字符,而最后一个元素为字符串的剩余部分。
字符串的替换
在 Java 中,String 类提供了 3 种字符串替换方法,分别是 replace()、replaceFirst() 和 replaceAll()。
replace() 方法
replace() 方法用于将目标字符串中的指定字符(串)替换成新的字符(串)。
其语法格式如下:
字符串.replace(String oldChar, String newChar)
oldChar 表示被替换的字符串;
newChar 表示用于替换的字符串。
replace() 方法会将字符串中所有 oldChar 替换成 newChar。
public class Main {
public static void main(String[] args) {
String words = "hello java,hello php";
System.out.println("原始字符串是'"+words+"'");
System.out.println("replace(\"l\",\"D\")结果:"+words.replace("l","D"));
System.out.println("replace(\"hello\",\"你好\")结果:"+words.replace("hello","你好 "));
words = "hr's dog";
System.out.println("原始字符串是'"+words+"'");
System.out.println("replace(\"r's\",\"is\")结果:"+words.replace("r's","is"));
}
}
原始字符串是'hello java,hello php'
replace("l","D")结果:heDDo java,heDDo php
replace("hello","你好")结果:你好 java,你好 php
原始字符串是'hr's dog'
replace("r's","is")结果:his dog
replaceFirst() 方法
replaceFirst() 方法用于将目标字符串中匹配某正则表达式的第一个子字符串替换成新的字符串
其语法形式如下:
字符串.replaceFirst(String regex, String replacement)
regex 表示正则表达式;
replacement 表示用于替换的字符串。
代码演示:
public class Main {
public static void main(String[] args) {
String words = "hello shuyv,hello DongKaizi";
String newStr = words.replaceFirst("hello","你好 ");
System.out.println(newStr);
}
}
你好 shuyv,hello DongKaizi
replaceAll() 方法
replaceAll() 方法用于将目标字符串中匹配某正则表达式的所有子字符串替换成新的字符串
其语法形式如下:
字符串.replaceAll(String regex, String replacement)
regex 表示正则表达式,
replacement 表示用于替换的字符串。
代码演示:
public class Main {
public static void main(String[] args) {
String words = "hello shuyv,hello DongKaizi";
String newStr = words.replaceAll("hello","你好 ");
System.out.println(newStr); // 输出:你好 shuyv,你好 DongKaizi
}
}
你好 shuyv,你好 DongKaizi
Java字符串比较
在 Java 中,比较字符串的常用方法有 3 个:
equals() 方法、equalsIgnoreCase() 方法、 compareTo() 方法。
equals() 方法
equals() 方法将逐个地比较两个字符串的每个字符是否相同。如果两个字符串具有相同的字符和长度,它返回 true,否则返回 false。
equals() 方法的语法格式如下:
str1.equals(str2);
str1 和 str2 可以是字符串变量, 也可以是字符串字面量。 例如, 下列表达式是合法的:
"Hello".equals(greeting)
代码演示:
public class Main {
public static void main(String[] args) {
String str1 = "DongKaizi";
String str2 = new String("DongKaizi");
String str3 = "shuyv";
System.out.println(str1.equals(str2)); // 输出 true
System.out.println(str1.equals(str3)); // 输出 false
}
}
equalsIgnoreCase() 方法
equalsIgnoreCase() 方法的作用和语法与 equals() 方法完全相同,唯一不同的是 equalsIgnoreCase() 比较时不区分大小写。
代码演示:
public class Main {
public static void main(String[] args) {
String str1 = "DongKaizi";
String str2 = new String("dongkaizi");
System.out.println(str1.equalsIgnoreCase(str2)); // 输出 true
}
}
equals() 与 == 的比较
equals() 比较的是字符串对象中的内容是否相同,而 == 比较的是俩个对象的引用是否相同,换句话说就是比较俩个对象内存中的指针指向是否相同。
代码说明:
public class Main {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); // 输出true
System.out.println(s1 == s2); // 输出false
}
}
compareTo() 方法
对于排序应用来说,必须知道一个字符是大于、等于还是小于另一个。一个字符串小于另一个指的是它在字典中先出现。而一个字符串大于另一个指的是它在字典后出现。
compareTo() 方法用于按字典顺序比较两个字符串的大小,该比较是基于字符串各个字符的 Unicode 值。
语法格式如下:
str.compareTo(String otherstr);
如果按照字典顺序 str 位于 otherster 参数之前,比较结果为一个负整数,如果 str 位于 otherstr 之后,比较结果为一个正整数;如果俩个字符串相等,则结果为0。
提示:如果两个字符串调用 equals() 方法返回 true,那么调用 compareTo() 方法会返回 0。
代码演示:
public class Main {
public static void main(String[] args) {
String str = "A";
String str1 = "a";
System.out.println("str=" + str);
System.out.println("str1=" + str1);
System.out.println("str.compareTo(str1)的结果是:" + str.compareTo(str1));
System.out.println("str1.compareTo(str)的结果是:" + str1.compareTo(str));
System.out.println("str1.compareTo('a')的结果是:" + str1.compareTo("a"));
}
}
str=A
str1=a
str.compareTo(str1)的结果是:-32
str1.compareTo(str)的结果是:32
str1.compareTo('a')的结果是:0
Java中容易混淆的空字符串和null
"" 是一个长度为 0 而且占内存的空字符串,在内存中分配一个空间,可以使用 Object 对象中的方法。
null 是空指针(引用),表示一个对象的值,没有分配内存,调用 null 的字符串的方法会报出空指针异常。
String str = null;
System.out.println(str.length());
报 NullPointerException 错。
判断字符串是否为空
if (str.length() == 0)
# 或者
if (str.equals(""))
空字符串也是一个 Java 对象,有自己的串长度(0)和内容(空)。不过,String 变量还可以存放一个特殊的值,名为 null ,这表示目前没有任何对象与改变量关联。要检查一个字符串是否为空,要使用以下条件:
if (str == null)
如果要检查一个字符串既不是空串也不是 null,这种情况就需要用以下爱条件:
if (str != null && str.length() != 0)
代码演示:
public static void main(String[] args) {
String str1 = new String();
String str2 = null;
String str3 = "";
System.out.println(str3.length()); // 空字符串""的长度为0
System.out.println(str2.length()); // 抛出空指针异常
System.out.println(str1); // 输出""
System.out.println(str1 == str2); // 内存地址的比较,返回false
System.out.println(str1.equals(str2)); // 值的比较,返回false
System.out.println(str2 == str3); // 内存地址的比较,返回false
System.out.println(str3.equals(str2)); // 值的比较,返回false
System.out.println(str1 == str3); // 内存地址的比较,返回false
System.out.println(str1.equals(str3)); // 值的比较,返回true
}
字符串查找
String 类的 indexOf() 方法和 lastIndexOf() 方法用于在字符串中获取匹配(串)的索引值。
indexOf() 方法
indexOf() 方法用于返回字符(串)在指定字符串中首次出现的索引位置,如果能找到,则返回索引值,否则返回 -1。
该方法主要有两种重载形式:
str.indexOf(value)
str.indexOf(value,int fromIndex)
- str 表示指定字符串;
- value 表示待查找的字符(串);
- fromIndex 表示查找时的起始索引,如果不指定 fromIndex,则默认从指定字符串中的开始位置(即 fromIndex 默认为 0)开始查找。
如下代码:
String s = "Hello Java";
int size = s.indexOf('v'); // size的结果为8
lastlndexOf() 方法
lastIndexOf() 方法用于返回字符(串)在指定字符串中最后一次出现的索引位置,如果能找到则返回索引值,否则返回 -1。
该方法也有两种重载形式:
str.lastIndexOf(value)
str.lastlndexOf(value, int fromIndex)
注意:lastIndexOf() 方法的查找策略是从右往左查找,如果不指定起始索引,则默认从字符串的末尾开始查找。
根据索引查找
String 类的 charAt() 方法可以在字符串内根据指定的索引查找字符,该方法的语法形式如下:
语法如下:
字符串名.charAt(索引值)
=public class Main {
public static void main(String[] args) {
String words = "today,monday,sunday";
System.out.println(words.charAt(0)); // 结果:t
System.out.println(words.charAt(1)); // 结果:o
System.out.println(words.charAt(8)); // 结果:n
}
}