java中string类的常用功能
package com.ifenx8.study.test;
public class Demo_Test {
/**
* @param args
*/
public static void main(String[] args) {
dome1();
//demo2();
//demo3();
//demo4();
//demo5();
//demo6();
}
public static void demo6() {
String s1 = "dsghgewghrerg";
//统计字符串的长度
int i = s1.length();
System.out.println(i);
//获取指定位置上的索引
char c = s1.charAt(10);
System.out.println(c);
//返回指定字符在次字符串中第一次出现的索引
int i1= s1.indexOf('g');
System.out.println(i1);
//返回指定字符串在此字符串中第一次出现的索引
int i2 = s1.indexOf("gh");
System.out.println(i2);
//返回指定字符在次字符串中指定的位置第一次出现的索引
int i3 = s1.indexOf('g', 3);
System.out.println(i3);
//返回指定的字符串在此字符串中指定位置中第一次出现的索引
int i4 = s1.indexOf("gh", 5);
System.out.println(i4);
//返回指定字符在此字符串中指定位置前第一次出现的索引
int i5 = s1.lastIndexOf('g', 10);
System.out.println(i5);
//返回指定字符串在此字符串的指定位置前第一次出现的索引
int i6 = s1.lastIndexOf("gh", 10);
System.out.println(i6);
//从指定位置开始截取字符串到最后
String s2 = s1.substring(2);
System.out.println(s2);
//从指定位置开始截取到直接位置结束
String s3 = s1.substring(2, 9);
System.out.println(s3);
}
public static void demo5() {
String s1= "abc";
String s2 = "abc";
String s3 = "aBc";
String s4 = "ab";
String s5 = "bc";
String s6 = "";
//判断两个字符串是否相等 大小也相等
System.out.println(s1.equals(s2));
//判断两个字符串是否相等 大小不相等
System.out.println(s1.equalsIgnoreCase(s3));
//判断大字符串是否包含小字符串
System.out.println(s1.contains(s4));
//判断是否包含开头字符串
System.out.println(s1.startsWith(s4));
//判断是否包含结束字符串
System.out.println(s1.endsWith(s5));
//判断是不是空字符串
System.out.println(s6.isEmpty());
}
public static void demo4() {
//把字符数组一部分转换成字符串1
char[] c = {'a','b','c','d','e'};
String s1 = new String(c,2,3);
System.out.println(s1);
String s2 = new String(c, 0, 5);
System.out.println(s2);
}
public static void demo3() {
//把字节数组一部分转换为字符串
byte[] b = {88,89,97,98,99,100};
String s1 = new String(b, 0, 3);
System.out.println(s1);
String s2 = new String(b, 0, 5);
System.out.println(s2);
//吧字符串一部分转换为字节数组
}
public static void demo2() {
//把字符数组转换成字符串1
char[] c = {'a','b','c','d'};
String s1 = new String(c);
System.out.println(s1);
//把字符数组一部分转换成字符串2
String s3 = String.valueOf(c);
System.out.println(s3);
//把字符串转化成字符数组
char[] chars = s1.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.print(chars[i] + " ");
}
}
public static void dome1() {
//把字节数组转化成字符串1
byte[] b = {97,98,99};
String s1 = new String(b);
System.out.println(s1);
//吧字符串转换成字节数组
byte[] bytes= s1.getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.print(bytes[i] + " ");
}
}
}