String类
Java将String视为对象处理,并封装了许多的方法供我们调用
常用构造函数
String() 默认的构造方法不需要任何参数,用于构造一个空的字符串String(char[] value) 通过char[]类型的数组构造一个新的String对象Strin(String original) original:已经存在的String对象 通过已经存在的String对象构造一个新的String对象,新的对象是原对象的副本 original:已经存在的String对象`
方法
常用
public int length()
public char charAt(int index)
该方法返回在String中index位置的字符 需要一个int类型的参数,index该参数用以表示获取第几个字符 public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
该方法用于将String从索引srcBegin开始,到srcEnd结束的字符复制到从desBegin开始的char[] dst中 warning在使用该方法之前,必须为char[] dst分配足够的空间以存放字符
比较
public int compareTo(String anotherString)
将调用该方法的String与参数anotherString进行比较,返回调用该方法的String的Unicode减anotherString的Unicode,相等返回0 public int compareToIgnoreCase(String str)
该方法可忽略字符串的大小写进行比较 warning该方法可能由于语言环境的不同而产生不够理想的结果,若要忽略字符串大小写进行比较,请首先调用Character.toLowerCase()或Character.toUpperCase()方法进行消除后,再使用public int compareTo(String anotherString)方法进行比较 public boolean equals(String anotherString)
将调用该方法的String与参数anotherString进行比较,当且仅当两个字符串长度相同,并且其中的相应字符都相等时(大小写敏感),结果为true,否则为false public boolean equalsIgnoreCase(String anotherString)
将调用该方法的String与参数anotherString进行比较,当且仅当两个字符串长度相同,并且其中的相应字符都相等时(大小写不敏感),结果为true,否则为false
转换
String转换为其他类型
类型 方法 booleanBoolean.getBoolean(String str)intInteger.parseInt(String str)longLong.parseLong(String str)floatFloat.parseFloat(String str)doubleDouble.parseDouble(String str)byteByte.parseByte(String str)charstr1.charAt(int i)
其他类型转换为String
方法 描述 String.valueOf(Type value)该方法支持所有基本类型转换为String,参数Type为可替换的类型名 Type.ToString该方法支持所有基本类型转换为String,参数Type为可替换的类型名
查找
方法 返回值 int indexOf(int ch)返回指定字符ch第一次出现的位置的索引 int indexOf(int ch, int fromIndex)返回指定字符ch在指定索引fromIndex之后第一次出现的位置的索引 int indexOf(String str)返回指定字符串str第一次出现的位置的索引 int indexOf(String str, int fromIndex)返回指定字符串cstr第一次出现的位置的索引 int lastIndexOf(int ch)返回指定字符ch最后一次出现的位置的索引 int lastIndexOf(int ch, int fromIndex)返回指定字符ch在指定索引fromIndex之后最后一次出现的位置的索引 int lastIndexOf(String str)返回指定字符串str最后一次出现的位置的索引 int lastIndexOf(String str, int fromIndex)返回指定字符串cstr最后一次出现的位置的索引
截取与拆分
public String substring(int beginIndex)
返回从指定索引beginIndex开始到字符串结束的字符串 public String substring(int beginIndex, int endIndex) -返回从beginIndex开始到endIndex - 1结束的字符串
替换与修改
String toLowerCase -将原字符串中所有字符转换为小写字符,并存储在新生成的String中String toUpperCase
将原字符串中所有字符转换为大写字符,并存储在新生成的String中 public String replace(char oldChar, char newChar)
将原字符串中oldChar替换为newChar,并返回新的字符串。若无oldChar可替换,则返回原来的字符串 public String concat(String str)
将调用该方法的字符串与参数str连接,并返回新的字符串。若参数str的长度为0,则返回原有字符串