1.键盘输入字符串
使用Scanner
类中的 nextLine()
方法。注意该方法如果与nextInt()
同时使用,会导致字符串无法录入。因为输入int数时,数后面会默认带一个行分割符/r/n
,而nextLine()
方法遇到 /r/n
就会停止录入。解决方法:数字和字符串都使用 nextLine()
方法输入,使用时再把数字字符串转化为数字。
2 .java
对String
类进行了封装 字符串字面值可以看做一个String对象,字符串是常量,存放于常量池,一经创建就不可以改变。 关于String
类中的" + "
:
The Java language PRovides special support for the string concatenation Operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.
String s = null
与 String s = ""
区别: String s = null
中s
没有任何对象指向,是一个null常量值。不可调用任何方法。否则会出现空指针异常;String s = ""
中s
指向一个具体的字符串对象,只不过这个字符串中没有内容,s
可以调用string
方法。
3 .String
类构造方法:将字节数组或者字符数组转成字符串
举两个byte[]
数组的栗子:
(1)String(byte[] bytes)
用平台默认编码方式解码把byte
数组转化为字符串
(2)String(byte[] bytes, int offset, int length
Constructs a new String by decoding the specified subarray of bytes using the platform’s default charset.用平台默认编码方式解码把byte数组一部分转化为字符串。offset
为初始索引值,length
为长度。
4 .String
获取方法:
(1)获取字符串的长度。length()
(2)指定位置的字符。char charAt(int index)
(3)获取指定字符的位置。如果不存在返回-1,所以可以通过返回值-1来判断某一个字符不存在的情况。 int indexOf(int ch) 返回第一次找到的字符index int indexOf(int ch,int fromIndex) 返回从指定位置开始第一次找到的index int indexOf(String str) 返回第一次找到的字符串index int indexOf(String str,int fromIndex) int lastIndexOf(int ch); int lastIndexOf(int ch,int fromIndex); int lastIndexOf(String str); int lastIndexOf(String str,int fromIndex); 以上为从后往前返回相应字符或字符串第一次出现的索引值
(4)截取子串。
String substring(int start)从start位开始,到length()-1为止
String substring(int start,int end)从start开始到end为止,包含start位,不包含end位
substring(0,str.length())
获取整串
5 .String 类判断方法:
(1)判断字符串中包含指定的字符串
boolean contains(String substring)(2)判断字符串是否以指定字符串开头
boolean startsWith(string)(3)判断字符串是否以指定字符串结尾
boolean endsWith(string)(4)判断判断字符串是否相同
boolean equals(string)(5)判断字符串内容是否相同,忽略大小写。
boolean equalsIgnoreCase(string)(6)判断字符串是否为空
boolean isEmpty(string)注:String类重写了Object中的equals方法。如果是字符串常量与字符串变量比较,一般把常量写在前面,调用equals方法,可以防止空指针异常。
6.String类的转换:通过构造方法可以将字符数组或者字节数组转成字符串。
(1)可以通过字符串中的静态方法,将字符数组转成字符串。
static String copyValueOf(char[] )static String copyValueOf(char[],int offset,int count);static String valueOf(char[])static String valueOf(char[],int offset,int count)(2)将基本数据类型或者对象转成字符串。
static String valueOf( )可以传递各基本数据类型 char,boolean,double,float,int,long
指的是直接调用对象toString()
方法,如果直接打印对象的引用,系统也会默认添加toString
方法 (3)将字符串转成大小写。
(4)将字符串转成数组。
char[] toCharArray()把字符串转化字符数组。
byte[] getBytes()把字符串转成字节数组,利用平台提供的编码方式把字符串编译成为计算机能够识别的语言;
7.其他
String replace(oldChar,newChar)将字符串中的字符进行内容替换
String replace(oldstring,newstring)将字符串进行内容替换,修改后变成新字符串,并不是将原字符串直接修改 String concat(string)
用于对字符串进行追加 String trim()
用于去除字符串两端的空格
用于比较两个字符串字典顺序。字典顺序:两个字符串相比不等要么是长度不同,要么是某些对应index
上字符不同,假设k是这样的最小索引。返回值为this.charAt(k)-anotherString.charAt(k)
;如果这样也比较不出大小,就直接比较两个字符串的长度,返回
新闻热点
疑难解答