【阿里云】Java面向对象开发课程笔记(四)——String类常用方法

1 String类常用方法

1.1 DOC文档组成

  文档地址
  左侧点击“java.lang”,再选择String查看文档。
任何一个类的文档有以下部分组成:

  • 类的相关定义,包括这个类的名字,又哪些父类,哪些借口;
  • 类的相关简介,包括类的基本使用;
  • 成员(Field)摘要:列出所有成员的信息项,属性就是一种成员;
  • 构造方法(Constructor)说明:列出该类中所有构造方法的信息;
  • 方法信息(Method):类中所有定义好的可以使用的方法;
  • 成员、构造、方法的详细信息。

1.2 字符串与字符数组

  字符串就是一个字符数组,所以String类中支持有字符数组转换为字符串以及字符串转换为字符的处理操作方法,这些
操作方法定义如下:

序号方法类型描述
01public String(char[] value)构造将字符数组中的所有内容变为字符串
02public String(char[] value,int offset,int count)构造将字符数组中的部分内容变为字符串
03public char charAt(int index)普通取得制定索引位置的字符,索引从0开始
04public char[] toCharArray()普通将字符串变为字符数组返回

范例:观察charAt方法

代码

public class StringDemo{
    public static void main(String args[]){
        String str = "hello";
        System.out.println(str.charAt(0)); //输出:h
        // 如果超过了字符串长度,会产生异常:java.lang.StringIndexOutOfBoundsException
        System.out.println(str.charAt(10));
    }
}

范例:字符串与字符数组转换

代码

public class StringDemo{
    public static void main(String args[]){
        String str = "helloworld";
        // 将字符串变为字符数组
        char data [] = str.toCharArray();
        for(int x = 0 ;x < data.length ; x++) {
            data [x] -= 32; // 转大写字母
            System.out.print(data[x] + " ");
        }
      System.out.println();
      System.out.println(new String(data)); //全部转换
      System.out.println(new String(data,5,5)); //部分转换
    }
} /* 输出结果:
H E L L O W O R L D 
HELLOWORLD
WORLD  */

范例:判断字符串是不是由数字所组成

  • 现在不知道字符串的长度以及包含的内容,最好转换为字符;
  • 判断每一位字符是否是“ ‘0’ ”~“ ‘9’ ”之间的内容,如果是则是数字,如果不是则不是数字。
    代码
public class StringDemo{
    public static void main(String args[]) {
        String str = "123432";
        System.out.println(isNumber(str) ? "由数字组成" : "由非数字所组成");
    }
        // 一般而言如果方法返回的是boolean类型,往往以isXxx()命名
        public static boolean isNumber(String str){
            char [] data = str.toCharArray();
            for (int x = 0; x < data.length; x++) {
                if (data[x] < '0' || data[x] > '9') {
                    return false;
                }
            }
          return true;    
        }
} // 输出结果:由数字组成 

1.3 字节与字符串

  字节更多的情况下是用于数据传输以及编码转换处理之中,在String类中提供有对字节操作的支持。
序号方法类型描述
01public String(byte[] bytes)构造将字节数组全部变为字符串
02public String(byte[] bytes,int offset,int length)构造将字节数组中的部分内容变为字符串
03public byte[] getBytes()普通字符串以字节数组方式返回
04public byte[] getBytes(String charsetName) throws UnsupportedEncodingException普通编码转换处理
范例:字符串转换为字节

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "helloworld";
        byte data[] = str.getBytes();
        for (int x = 0; x < data.length; x++) {
            System.out.print(data[x] + ".");
        }
    }
} // 输出结果:104.101.108.108.111.119.111.114.108.100.
  字节不适合处理中文,而只有字符适合处理中文,并且按照程序概念,一个字符=2个字节:字节只适合处理二进制数据。

1.4 字符串比较

  “equals()”方法本身可以进行区分大小写相等判断,除了这个方法,String类还提供如下几个比较操作:
序号方法类型描述
01public boolean equals(String anObject)普通区分大小写的比较
02public boolean equalsIgnoreCase(String anotherString)普通不区分大小写的比较
03public int compareTo(String anotherString)普通比较两个字符串的大小关系
范例:不区分大小写比较

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "hello";
        System.out.println("Hello".equalsIgnoreCase(str)); // true
        System.out.println("Hello".equals(str)); // false
    }
}
  在String类中compareTo()方法是一个非常重要的方法,该方法返回的是一个int型数据,该数据会根据大小返回三类内容:
  • 相等:返回0;
  • 小于:返回的内容小于0;
  • 大于:返回的内容大于0。

范例:观察compareTo

代码

public class StringDemo {
    public static void main(String args[]) {
        System.out.println("A".compareTo("a")); // -32
        System.out.println("A".compareTo("A")); // 0
        System.out.println("a".compareTo("A")); // 32
        System.out.println("ab".compareTo("ac")); // -1  
        System.out.println("周".compareTo("赵")); // -14605 
    }
}

  compareTo()是唯一一个可以区分大小关系的方法。

1.5 字符串查找

  从一个完整的字符串中判断指定的内容是否存在。

序号方法类型描述
01public boolean contains(String s)普通判断一个子字符串是否存在
02public int indexOf(String str)普通从头开始查找指定字符串的位置,查到了返回位置的开始索引,若查不到,返回-1
03public int indexOf(String str,int fromIndex))普通从指定位置开始查找子字符串的位置
04public int lastIndex(String str))普通由后向前开始查找子字符串的位置
05public int lastIndexOf(String str,int fromIndex))普通从指定位置由后向前查找子字符串的位置
06public boolean startsWith(String prefix))普通从头开始判断是否以指定的字符串开头
07public boolean startsWith(String prefix,int toffset))普通从指定位置开始判断是否以指定的字符串开头
08public boolean endsWith(String suffix))普通判断是否已指定的字符串结尾

范例:字符串查找,最方便的就是contains(),直接返回boolean类型

代码

public class StringDemo {
    public static void main(String args[]) {
         String str = "helloworld";
         System.out.println(str.contains("world")); // true
    }
}

  该判断形式是从JDK1.5之后开始追加的,之前若想要实现与之类似的功能,必须依靠indexOf()方法完成。
范例:使用indexOf()方法

代码

public class StringDemo {
    public static void main(String args[]) {
         String str = "helloworld";
         System.out.println(str.indexOf("world")); // 5,w开头的索引
         System.out.println(str.indexOf("java")); // -1,没有查到
    }
}

  建议使用contains()方法完成。
  使用indexOf()需要注意的是,如果内容重复它只能返回查找的第一个位置。
范例:使用indexOf()方法

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "helloworld";
        System.out.println(str.indexOf("l")); // 2
        System.out.println(str.indexOf("l",5)); // 8
        System.out.println(str.lastIndexOf("l")); // 8
    }
}

范例:判断开头或结尾

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "**@@helloworld##";
        System.out.println(str.startsWith("**")); // 2
        System.out.println(str.startsWith("@@",2)); // 8
        System.out.println(str.endsWith("##")); // 8
    }
}

  一些参数会利用某些标记做一些特殊处理,此时就需要使用到startsWith()和endsWith()。

1.6 字符串替换

  使用一个指定的新的字符串替换掉已有的字符串数据,字符串替换操作方法如下:

序号方法类型描述
01public String replaceAll(String regex,String replacement)普通替换所有指定内容
02public String replaceFirst(String regex,String replacement)普通替换首个内容

范例:实现字符串替换处理

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "helloworld";
        System.out.println(str.replaceAll("l","_"));  // he__owor_d
        System.out.println(str.replaceFirst("l","_"));  // he_loworld
    }
}

1.7 字符串拆分

  使用特定字符串将字符串进行分割处理,也就是说可以将一个完整的字符串按照指定的分割符划分为若干个子字符串。

序号方法类型描述
01public String[] split(String regex)普通将字符串全部拆分
02public String[] split(String regex,int limit)普通将字符串部分拆分,该数组长度就是limit极限

范例:实现字符串拆分处理

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "hello world hello mldn";
        String result1 [] = str.split(" "); // 按照空格拆分
       for (int x = 0 ; x < result1.length ; x++){
           System.out.println(result1[x]); 
       }
          System.out.println("\n"); 
           String result2 [] = str.split(" ",2);
           for (int x = 0 ; x < result2.length ; x++){
               System.out.println(result2[x]); 
           }
    }
}
  • 输出结果
hello
world
hello
mldn


hello
world hello mldn

  以上拆分都很容易,如果发现有些内容无法拆分开,就需要使用“\”转义。
范例:拆分ip地址·

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "192.168.1.1";
        //String result [] = str.split("."); 无法拆分 
        String result [] = str.split("\\."); 
       for (int x = 0 ; x < result1.length ; x++){
           System.out.println(result[x]); 
       }
    }
} /* 输出:
192
168
1
1  */

范例:拆分|和:

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "Smith:10|Allen:20|Jack:15";
        String result [] = str.split("\\|");
        for (int x = 0 ; x < result.length ; x++){
          String temp [] = result[x].split(":");
              System.out.println(temp[0] + " = " + temp [1] );
      }
    }
} /* 输出:
Smith = 10
Allen = 20
Jack = 15  */

  这种代码以后会经常出现,该程序必须会操作。

1.8 字符串截取

  从一个完整的字符串中截取出部分内容,截取方法如下:

序号方法类型描述
01public String substring(int beginIndex)普通从指定索引截取到结尾
02public String substring(int beginIndex,int endIndex)普通截取部分内容

范例:字符串截取

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "helloworld";
        System.out.println(str.substring(5)); // world
        System.out.println(str.substring(0,5)); // hello
    }
}

  程序中的字符串截取索引从0开始,而且只能够设置正整数,不能使用负数。

1.9 字符串其它操作方法

  在String类中也定义有一些比较小的操作方法。

序号方法类型描述
01public String trim()普通去掉字符串左右空格,保留中间空格
02public String toUpperCase()普通字符串转大写
03public String toLowerCase()普通字符串转小写
04public String intern()普通字符串入对象池
05public String concat(String str)普通字符串连接,等同于“+”
06public int length()普通取得字符串长度操作
07public boolean isEmpty()普通从指定位置开始判断是否为空字符串(但不是null,而是长度为0)

范例:trim()

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "   hello world   ";
        System.out.println(" [" + str + "] "); // [  hello world  ]
        System.out.println(" [" + str.trim() + "] "); //  [hello world]
    } 
}

范例:大小写转换

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "Hello123World";
        System.out.println(str.toUpperCase()); // HELLO123WORLD
        System.out.println(str.toLowerCase()); // hello123world
    } 
}

  使用这两个方法,非字母不进行转换。
范例:字符串连接

代码

public class StringDemo {
    public static void main(String args[]) {
        String str1 = "HelloWorld";
        String str2 = "Hello".concat("World");
        System.out.println(str2); // HelloWorld
        System.out.println(str1 == str2); // false:未入池
    } 
}

范例:length()

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "HelloWorld";
        System.out.println(str.length); // 10
    } 
}

  在数组上有一个格式“数组名称.length属性”,但在String类中的length()是一个方法,方法必须通过对象才可以调用,而且方法后面一定有“()”存在。
范例:isEmpty()

代码

public class StringDemo {
    public static void main(String args[]) {
        System.out.println("hello".isEmpty()); // fasle
        System.out.println("".isEmpty()); //true
        System.out.println(new String().isEmpty()); // true
    } 
}

  String类中没有提供首字母大写的方法,如果要想使用,必须自己实现。
范例:实现首字母大写

代码

public class StringDemo {
    public static void main(String args[]) {
        String str = "hello";
        String result = initcap(str);
        System.out.println(result);
    } 
public static String initcap(String str){
      if (str == null || str.isEmpty()){
           return str; 
      }else if ( str.length() > 1 ){
           return str.substring(0,1).toUpperCase() + str.substring(1);
     }else {
              return str.toUpperCase();
             }
  }
} // Hello

  这种首字母大写的程序使用频率很高。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值