上一篇介绍了 String 中的几个常用构造方法,由 String 这个核心对象发散出去关于字符的编码,字符的字节表达,对 GC 的影响,正则表达式,模式匹配,这可能是 Java 里内涵最丰富的对象了。今天先讲一下 API 中定义的一些常用方法。

1、length 方法

length()
Returns the length of the sequence of characters represented by this object.

返回字符串的长度(或者理解为对应字符数组的长度),如果字符串对象的值为 null 则抛出空指针异常(java.lang.NullPointerException)。

String str = "你好,谷歌!";
String str1 = "Hello, google!";
System.out.println(str.length());
System.out.println(str1.length());

运行结果为:

6
14

2、isEmpty 方法

public boolean isEmpty()
Returns true if length() is 0, otherwise false.

如果字符串的长度为 0,则返回 true, 否则返回 false。

如果字符串对象的值为 null 则抛出空指针异常(java.lang.NullPointerException)。

注意:因为在使用过程中,会忘记字符串值为 null 的情况,所有判断字符串为空尽量使用 org.apache.commons.lang.StringUtils 中封装的几个方法:

  1)isEmpty 方法 

     

     源码如下:

public static boolean isEmpty(String str) {
  return str == null || str.length() == 0;
}

  2)isNotEmpty 方法

     

    源码如下:

public static boolean isNotEmpty(String str) {
  return !StringUtils.isEmpty(str);
}

  3)isBlank 方法

       

     源码如下:

public static boolean isBlank(String str) {
  int strLen;
  if (str == null || (strLen = str.length()) == 0) {
    return true;
  }
  for (int i = 0; i < strLen; i++) {
    if ((Character.isWhitespace(str.charAt(i)) == false)) {
      return false;
    }
  }
  return true;
}

  4)isNotBlank 方法

     

       源码如下:

public static boolean isNotBlank(String str) {
  return !StringUtils.isBlank(str);
}

3、charAt 方法

charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

返回索引位置的字符(String 本身就是 char[] 数组类型)

参数为 int index,范围为从 0 到 length() -1

如果索引是负数或者大于或等于字符串的长度,则会抛出索引越界异常 IndexOutOfBoundsException。

String str = "hello, google!";
System.out.println(str.charAt(0));
System.out.println(str.charAt(str.length() - 1));

运行结果:

h
!

4、getByte 方法

getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

两个方法均返回字符串对应的(指定编码方式的)字节类型数组。

return new String(str.getBytes("iso-8859-1"), "UTF-8");

5、equals 方法

equals(Object anObject)
Compares this string to the specified object.

比较两个对象是否内容相等,话不多说,直接上经典的源码实现:

通常将常量放在前面,变量放在后边

String str = "hello, google";
if ("hello, baidu".equals(str)) {
  System.out.println("Are you kidding me?");
} else {
  System.out.println("It's OK!");
}

输出结果:

It's OK!

6、compareTo 方法

compareTo(String anotherString)
Compares two strings lexicographically.

按照字典顺序比较两个字符串,相等返回 0,在 anotherString 前面返回小于 0 的值,否则返回大于 0 的值。

String str = "hello, google";
System.out.println("compare with baidu: " + str.compareTo("hello, baidu"));

输出结果:

compare with baidu: 5

该方法应用于 Java 中的比较器的实现(内部和外部两种),有关知识参阅:Java_两种比较器的实现

PS:外部比较器可以用匿名内部类实现较为简单,或者用 java8 中的 lambda 表达式更是简单,相关知识参阅:Java8 初体验(一)lambda 表达式语法

7、startsWith 方法 和 endsWith 方法

startsWith(String prefix)
Tests if this string starts with the specified prefix.

startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.

endsWith(String suffix)
Tests if this string ends with the specified suffix.

判断字符串是否已给定的字符串开头或者结尾(这里的参数只能是字符串,不支持正则表达式)

String str = "hello, google";
System.out.println(str.startsWith("google", 7));

输出结果:

true

8、hashCode 方法

Returns a hash code for this string.

返回该字符串的哈希值,在初始化对象时,如果该对象可能进行比较,则需要根据要比较的属性重写 equals() 和 hashCode() 方法。

9、indexOf 方法 和 lastIndexOf 方法

indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.

indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.

indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.

lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.

lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

返回的均是索引值(int),还是看图直观:

String str = "hello, google";
System.out.println("the second g's index is: " + str.indexOf(103, 8));
System.out.println("google's index is: " + str.indexOf("google"));

输出结果:

g's index is: 10
google's index is: 7

10、substring 方法

substring(int beginIndex)
Returns a string that is a substring of this string.

substring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.

这个方法估计用到的频率最高了,分隔字符串方法,会抛出索引越界异常。

String str = "hello, google";
System.out.println(str.substring(0, 5));

输出结果:

hello

记住一点就好:前闭后开 [beginIndex, endIndex)

Java 中 String 的常用方法(一)的更多相关文章

  1. java中String的常用方法

    java中String的常用方法1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); int len= ...

  2. Java中String的常用方法总结

    Java中String的常用方法总结 1.length()字符串的长度 String str="HelloWord"; System.out.println(str.length( ...

  3. JAVA中String类常用方法 I

    String类常用方法有: int length() -– 返回当前字符串的长度 int indexOf(int ch) -– 查找ch字符在该字符串中第一次出现的位置 int indexOf(Str ...

  4. Java中String类常用方法(字符串中的子字符串的个数)

    重点内容 4种方法: 1.int indexOf(String str)返回第一次出现的指定子字符串在此字符串中的索引. 2.int indexOf(String str, int startInde ...

  5. Java 中 String 的常用方法(二)

    本文介绍剩下的一些常用的 String 中的方法. 1.replace 方法 .replaceFirst 方法和 replaceAll 方法 replace(char oldChar, char ne ...

  6. Java 中String常用方法

    java中String的常用方法 1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); int len ...

  7. Java中String常用方法

    java中String的常用方法1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); int len= ...

  8. java基础——String的常用方法

    java中String的常用方法 1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); i nt le ...

  9. Java中String类的方法及说明

    String : 字符串类型 一.      String sc_sub = new String(c,3,2);    //      String sb_copy = new String(sb) ...

随机推荐

  1. 使用Docker部署ASP.NET Core应用程序实践

    前言 最近把很火的Docker给看了,于是就磨拳擦掌要去实践一下.于是就拿之前一个aps.net core的项目(已被停止)去练手.该项目之前在ubuntu14.04上确保可以正常运行,所以docke ...

  2. mysql快速插入大数据

    说的是插入数据,这个倒像是载入数据. 上一篇,是按照插入数据来写的,就是insert into,当时插入一万条实在是太慢了,大概是286734毫秒. insert into table values, ...

  3. [Git01]Pro Git 第三章 分支 读书笔记

    [git]分支   Git 的分支模型称为“必杀技特性”,而正是因为它,将 Git 从版本控制系统家族里区分出来. Git 有何特别之处呢?Git 的分支可谓是难以置信的轻量级,它的新建操作几乎可以在 ...

  4. 修改mysql的时间/时区

    # 背景 往db中insert数据发现时间不对,因为是新DB,所以猜测是mysql设置不对 # 解决方法 方法一:通过mysql命令行模式下动态修改 show variables like " ...

  5. asp.net 错误页面自定义

    在我们上网浏览信息的时候,总会有出现404页面的时候,在我们开发的时候也可以自定义这些页面.刚回这次项目中也使用到了,就在网上找到一些方法,今天就把这些方法重新写一遍加深记忆. 在项目的web.con ...

  6. .net core 应用Nancy快速实现轻量级webapi

    目前大量数据接口均采用API的方式为各类应用提供数据服务.Nancy是.net下实现webapi的一个轻量级的框架,可以快速搭建一个api服务环境,是一种快速建立api服务的不错选择. 本文记录.ne ...

  7. 如何关闭SQL进程

    --通过下面的查询得到trace ID select * from sys.traces --修改下面的@traceid参数,关闭,删除对应的trace exec sp_trace_setstatus ...

  8. 【总结】 BZOJ前100题总结

    前言 最近发现自己trl,所以要多做题目但是Tham布置的题目一道都不会,只能来写BZOJ HA(蛤)OI 1041 复数可以分解成两个点,所以直接把\(R^2\)质因数分解一下就可以了,注意计算每一 ...

  9. linux中使用unzip命令中文乱码解决办法

    今天在使用unzip进行解压缩文件时,发现解压出的文件中文乱码,最后使用如下命令解决: unzip -O CP936 xxx.zip 特此记录一下.

  10. mysql 批量更新的四种方法

    批量更新的方法: 1 ) 逐条更新 代码如下: UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value'; 如果更新 ...