ToB企服应用市场:ToB评测及商务社交产业平台

标题: 零基础学Java(4)字符串 [打印本页]

作者: 大号在练葵花宝典    时间: 2022-8-23 10:32
标题: 零基础学Java(4)字符串
字符串

从概念上讲,Java字符串就是Unicode字符序列。例如,字符串"Java\u2122"由5个Unicode字符J、a、v、a和™组成。Java没有内置的字符串类型,而是在标准Java类库中提供了一个预定义类,很自然地叫做String。每个双引号括起来的字符串都是String类中的一个实例
  1. String e = "";  // an empty string
  2. String greeting = "Hello"
复制代码
 
子串

String类的substring方法返回字符串的子字符串。
语法
  1. public String substring(int beginIndex)
  2. public String substring(int beginIndex, int endIndex)
复制代码
参数
例子
  1. public class FirstSample {
  2.     public static void main(String[] args) {
  3.         String Str = "This is text";
  4.         System.out.print("返回值 :" );
  5.         System.out.println(Str.substring(4) );  // 从第4个索引开始到结束
  6.         System.out.print("返回值 :" );
  7.         System.out.println(Str.substring(4, 10) );  // 从第4个索引开始到第10个结束,不包括第10个
  8.     }
  9. }
复制代码
结果
  1. 返回值 : is text
  2. 返回值 : is te
复制代码
现在我们知道了substring的用法,接下来看看源码
 
源码分析
  1.     /**
  2.      * Returns a string that is a substring of this string. The
  3.      * substring begins at the specified {@code beginIndex} and
  4.      * extends to the character at index {@code endIndex - 1}.
  5.      * Thus the length of the substring is {@code endIndex-beginIndex}.
  6.      * <p>
  7.      * Examples:
  8.      * <blockquote><pre>
  9.      * "hamburger".substring(4, 8) returns "urge"
  10.      * "smiles".substring(1, 5) returns "mile"
  11.      * </pre></blockquote>
  12.      *
  13.      * @param      beginIndex   the beginning index, inclusive.
  14.      * @param      endIndex     the ending index, exclusive.
  15.      * @return     the specified substring.
  16.      * @exception  IndexOutOfBoundsException  if the
  17.      *             {@code beginIndex} is negative, or
  18.      *             {@code endIndex} is larger than the length of
  19.      *             this {@code String} object, or
  20.      *             {@code beginIndex} is larger than
  21.      *             {@code endIndex}.
  22.      */
  23.     // 定义了substring方法,有两个参数beginIndex和endIndex
  24.     public String substring(int beginIndex, int endIndex) {
  25.         // 如果起始索引小于0,抛出异常
  26.         if (beginIndex < 0) {
  27.             throw new StringIndexOutOfBoundsException(beginIndex);
  28.         }
  29.         // 如果结束索引大于值的长度,抛出异常
  30.         if (endIndex > value.length) {
  31.             throw new StringIndexOutOfBoundsException(endIndex);
  32.         }
  33.         // 子串的长度
  34.         int subLen = endIndex - beginIndex;
  35.         // 如果子串的长度小于0,抛出异常
  36.         if (subLen < 0) {
  37.             throw new StringIndexOutOfBoundsException(subLen);
  38.         }
  39.         // 如果起始索引等于0并且结束索引等于字符串的长度,那么返回字符串本身,否则创建一个新的字符串
  40.         return ((beginIndex == 0) && (endIndex == value.length)) ? this
  41.                 : new String(value, beginIndex, subLen);
  42.     }
复制代码
 
拼接

与绝大多数程序设计语言一样,Java语言允许使用+号连接(拼接)两个字符串。这个没什么说的。
但是要注意:当将一个个字符串与一个非字符串的值进行拼接时,后者会转换字符串。例如:
  1. int age = 13;
  2. String x = "jkc" + age;
复制代码
结果是jkc13
 
如果我们需要把多个字符串放在一起,并用一个界定符分隔,可以使用静态join方法:
  1. public class FirstSample {
  2.     public static void main(String[] args) {
  3.         System.out.print("返回值 :" );
  4.         System.out.println(String.join("/", "A", "B", "C", "D"));
  5.     }
  6. }
复制代码
结果
  1. 返回值 :A/B/C/D
复制代码
join方法有两种重载方法,这里只介绍以下这一种
  1. public static String join(CharSequence delimiter, CharSequence… elements)
复制代码
String.join("/", "A", "B", "C", "D")的意思就是用分隔符/将ABCD这4个字符串连接起来,结果自然就是A/B/C/D
 
不可变字符串

在Java中是不能修改Java字符串中的单个字符的,所以再Java文档中将String类对象称为是不可变的,如果真的想修改,可以提取想保留的子串,再与希望替换的字符拼接:
  1. greeting = greeting.substring(0, 3) + "p!";
复制代码
 
检测字符串是否相等

可以使用equals方法检测两个字符串是否相等,语法:
  1. s.equals(t)
复制代码
如果字符串s与字符串t相等,则返回true;否则,返回false。
要想检测两个字符串是否相等,而不区分大小写,可以使用equalsIsIgnoreCase方法。
  1. "Hello".equalsIgnoreCase("hello");
复制代码
注意:一定不要使用==运算符检测两个字符串是否相等!这个运算符只能够确定两个字符串是否在同一个内存地址上。当然,如果字符串在同一个内存地址上,它们必然相等。但是,完全有可能将内容相同的多个字符串放置在不同的内存地址上。
  1. public class FirstSample {
  2.     public static void main(String[] args) {
  3.         String greeting = "Hello";
  4.         System.out.println("变量greeting的内存地址为:" + System.identityHashCode(greeting));
  5.         System.out.println("hello的内存地址为:" + System.identityHashCode(greeting));
  6.         if (greeting == "Hello") {
  7.             System.out.println("同一个内存地址,相等");
  8.         }
  9.         String x =  greeting.substring(0, 3);
  10.         System.out.println("变量x的内存地址:" + System.identityHashCode(x));
  11.         if (x == "Hel") {
  12.             System.out.println("内存地址不同");
  13.         }
  14.     }
  15. }
复制代码
如果虚拟机始终将相同的字符串共享,就可以使用==运算符检测是否相等。但实际上只有字符串字面量是共享的,而+或substring等操作得到的字符串并不共享。因此,千万不要使用==运算符测试字符串的相等性,以免在程序中出现这种最糟糕的bug,看起来这种bug就像随机产生过的间歇性错误。
 
空串与Null串

空串""是长度为0的字符串。可以调用以下代码检查一个字符串是否为空:
  1. if (str.length() == 0)
复制代码
  1. if (str.equals(""))
复制代码
空串是一个Java对象,有自己的串长度(0)和内容(空)。不过String变量还可以存放一个特殊的值,名为null,表示目前没有任何对象与该变量关联。要检查一个字符串是否为null,要使用以下条件:
  1. if (str == null)
复制代码
有时要检查一个字符串既不是null也不是空串,这种情况下就需要使用以下条件:
  1. if (str !=null && str.length() != 0)
复制代码
首先要检查str不为null,如果在一个null值上调用方法,会出现错误。
 
String API

Java中的String类包含了50多个方法,接下来介绍一些最常用的方法
java.lang.String 1.0
构建字符串

  有些时候,需要由较短的字符串构建字符串,例如,按键或来自文件中的单词。如果采用字符串拼接的方式来达到这个目的,效率会比较低。每次拼接字符串时,都会构建一个新的String对象,既耗时,又浪费空间。使用StringBuilder类就可以避免这个问题发生。
  如果需要用许多小段的字符串来构建一个字符串,那么应该按照下列步骤进行。首先,构建一个空的字符串构建器:
  1. StringBuilder builder = new StringBuilder();
复制代码
当每次需要添加一部分内容时,就调用append方法
  1. builder.append("jkc");
  2. builder.append("jkc2");
  3. builder.append("jkc3");
复制代码
在字符串构建完成时就调用toString方法,将可以得到一个String对象,其中包含了构建器中的字符序列。
  1. String completedString = builder.toString();
复制代码
下面的API包含了StringBuilder类中的重要方法

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4