字符串处理 String类

java的字符串处理技术主要包括:
String类在程序运行初始化后不能改变。
StringBuffer类字符串的内容可以动态的改变。

String类

String 类位于java.lang包中,
String 类不需要import语句就可以用String 来实例化对象。
String 类主要用来处理在程序运行初始化后其内容不能被改变的字符串。

字符串的构造

字符串常量:使用双引号分割的一系列java合法字符。
在用赋值运算符进行字符串初始化时,JVM自动为每个字符串生产一个String类的实例。
字符串的声明:

String s;

字符串的创建:

//可以使用String类的构造方法:

    s = new String("We are students");

//也可以写成:

    s = "We are students";

//声明和实例化对象也可以一步完成:

    String s = new String("We are students");
//或

    String s = "We are students";

String类的构造方法:

构造方法 说明
String() 分配一个新的不含有字符的String()
String(byte[]) 用默认的字符编码方式转换指定的字节数组生成一新的String
String(byte[],string) 用指定的字符编码方式转换指定的字节数组生成一新的String
String(byte[],int,int) 用默认的字符编码方式转换指定的字节子数组生成一新的String
String(byte[],int,int,string) 用指定的字符编码方式转换指定的字节子数组生成一新的String
String(char[]) 分配一个新的String,它包含有当前字符数组参数中的字符
String(char[],int,int) 分配一个新的String,它包含字符数组参数的一子数组
String(String) 分配一个新的String,它包含有与字符串参数相同的字符序列
String(StringBuffer) 分配一个新的String,它包含有当前字符串缓冲区参数中的字符序列

利用String 类提供的构造方法,可以生成空的字符串或者由其他基本数据类型生成字符串对象。
(1)空String实例

String strDemo = new String();

(2)字符数组构造字符串

char cDemo1[] = {'2','3','4','5'};
char cDemo2[] = {'1','2','3','4','5'};
String strDemo1 = new String(cDemo1);
String strDemo2 = new String(cDemo2,1,4);
System.out.println(strDemo1);       //2345
System.out.println(strDemo2);       //2345

(3) 字节数组构造字符串:

byte bDemo1[] = {66,67,68};
byte bDemo2[] = {65,66,67,68};
String strDemo1 = new String(bDemo1);
String strDemo2 = new String(bDemo2,1,3);
System.out.println(strDemo1);       //BCD
System.out.println(strDemo2);   //BCD

String 类的常用方法

1.字符串长度计算

length()
方法的定义: public int length()
该方法返回字符串中16-bit的 Unicode字符的数量。
例如:

String s = "we are students",tom ="我们是学生";
int n1,n2,n3;
n1 =s.length();
n2 = tom.length();
n3 ="我的爱好".length();
System.out.println(n1);    // 15
System.out.println(n2); // 5
System.out.println(n3); // 4

2.字符串比较

1)equals()
在String类中的定义:public boolean equals(String s)
该方法用来比较当前字符串对象的实体是否与参数指定的字符串S的实体相同。

String a1 = new String("we are students");
String a2 = new String("We are students");
String a3 = new String("we are students");
System.out.println(a1.equals(a2));  //false
System.out.println(a1.equals(a3));  //true

注意:a1==a3的值是false,因为字符串是对象,a1,a2,a3都是引用。其引用位置在内存中是不同的。

2)equalsIgnoreCase()
在String类中的定义:public boolean equalsIgnoreCase(String s)
该方法用来比较当前字符串对象的实体是否与参数指定的字符串S的实体相同,同时忽略大小写。

String a1= new String("ABC"),a2= new String("abc");
System.out.println( a1.equalsIgnoreCase(a2)); //true

3 ) sartsWith()
在String类中的定义 public boolean startsWith(String s)
该方法判断当前字符串对象的前缀是否是参数指定的字符串 s.

String tom = "22030269021",jerry = "21098760532"
tom.startsWith("220")       //true;
jerry.startsWith("220")     //false

4) endsWith()
在String类中的定义 public boolean endsWith(String s)
该方法判断当前字符串对象的后缀是否是参数指定的字符串 s.

String tom = "22030269021",jerry = "21098760022"
tom.endsWith("021")         //true;
jerry.startsWith("021")     //false

5) regionMatches()
在String类中的定义:
public boolean regionMatches(int firstStart,String other,int otherStart,int length)

public boolean regionMathes(boolean ingoreCase,int firstStart,String other,int otherStart,int length)
从当前字符串参数 firstStart指定的位置开始处,取长度为length的一个子串,并将这个子串和参数 other指定的一个子串进行比较。其中,ohter 指定的子串是从参数 otherStart指定的位置开始,从other中取出长度为 length的一个子串。如果两个子串相同方法就返回 true,否则 返回 false.注意,字符串的位置编号从 0开始。

String a1 = "we are student";
String a2 = "We are student";
a1.regionMatches(0, a2, 0,14);          // false
a1.regionMatches(true,0, a2, 0,14);     // true;

6) compareTo()
在String类中的定义 public int compareTo(String s)
按照字典顺序与参数 s指定的字符串比较大小。
如果当前字符串与 s 相同,该方法返回值 0;
如果当前字符串对象大于 s 该方法 返回正值;
如果当前字符串对象小于 s 该方法返回负值。

String str = "abcde";
str.compareTo("boy");   //<0
str.compareTo("aba");   //>0
str.compareTo("abcde")  //=0

7)compareToIgnoreCase()
在String类中的定义 compareToIgnoreCase(String s)
同 compareTo()方法,比较时忽略大小写。

将字符串按照字典顺序重新排列

String a[] = {"Java","Basic","C++","Fortran","SmallTalk"};
for(int i=0;i<a.length-1;i++){
    for(int j=i+1; j<a.length;j++){
        if(a[j].compareTo(a[i])<0){
            String temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
     }
    for(int t=0;t<a.length;t++){
        System.out.print(a[t]+" ");
     }
     System.out.println("");
}
//结果:
// Basic Java C++ Fortran SmallTalk 
// Basic C++ Java Fortran SmallTalk 
// Basic C++ Fortran Java SmallTalk 
// Basic C++ Fortran Java SmallTalk 

3.字符串检索:

搜索指定字符或字符串在字符串中出现的位置,用于字符或是字符串在字符串中的定位。
方法的声明格式如下:
public int indexOf(int ch)
public int indexOf(int ch,int fromIndex)
public int indexOf(String str)
public int indexOf(String str,int fromIndex)
上述4个重载的方法分别用于在字符串中定位指定的字符和字符串,并且在方法中可以通过fromIndex来指定匹配的起始位置。
如果没有检索到字符或字符串,该方法返回的值是-1.

String strSource = "I love Java";
int nPosition;
nPosition = strSource.indexOf('v');     //4
nPosition = strSource.indexOf('a',9);   //10
nPosition = strSource.indexOf("love");  //2
nPosition = strSource.indexOf("love",0);//2

搜索指定字符或字符串在字符串最后出现的位置:
public int lastIndexOf(int ch)
public int lastIndexOf(int ch,int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str,int fromIndex)
如果没有检索到字符或字符串,该方法返回的值是-1.

4.字符串截取

方法的声明格式如下:
public String substring(int beginIndex);
该方法将获得一个当前字符串的子串,该子串是从当前字符串的 beginIndex 处截取到最后所得到的字符串。
public String substring(int beginIndex, int endIndex)
该方法将获得一个当前字符串的子串,该子串是从当前字符串的 beginIndex 处截取到 endIndex-1 结束所得到的字符串。

String strSource = "java is interesting";
String strNew1  = strSource.substring(5);    //"is interesting"
String strNew2  = strSource.substring(5,6); //"i"

5.字符串替换

方法的声明格式如下:
public string replace(char oldChar,char newChar)
字符串 s 对象调用该方法可以获得一个串对象,这个串对象 使用参数 newChar指定的字符 替换 s 中由 oldChar 指定的所有字符而得到的字符串。

public String replaceAll(String old,String new)
字符串 s 对象调用该方法可以获得一个串对象,这个串对象 使用参数 new指定的字符串 替换 s 中由 old 指定的所有字符串而得到的字符串。
public String trim()
字符串 s 对象调用该方法可以获得一个串对象,该字符串对象是 s 去掉前后空格后的字符串。

String strSource = "java is interesting and interchanges";
String strNew1 = strSource.replace('s','S');            //"java iS intereSting and interchangeS"
String strNew2  = strSource.replaceAll("inter","easy"); // "java is easyesting and easychanges"

6.其它的一些方法

1)字符串大小转换

public String toUpperCase(Locale locale)    //仅对指定的位置进行转换。
public String toUpperCase()
public String toLowerCase(Locale locale)        //仅对指定的位置进行转换。  
public String toLowerCase()

2)转换为字符串数组
public char[] toCharArray()
该方法用于将字符串转换为字符串数组。该方法的返回值类型为字符串数组。

String strSource = new String("Java is interesting");
char[] ch;
ch = strSource.toCharArray();   //Java is interesting

3) 字符串到字符数组之间的转换
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
该方法用于将字符串中的字符内容复制到字符数组中。其中 srcBegin 为复制的起始位置,srcEnd -1 为复制的终止位置,字符串数组 dst 为目的字符数组, dstBegin 为目的字符串数组的复制起始位置。

String strSource = new String("I love Java");
char[] ch={'a','b','c','d','e'};
strSource.getChars(0,2, ch, 0); // I cde

4) 连接两个字符串
public string concat(String str)
该方法用于将两个字符串连接在一起,与字符串的 + 操作功能相同。

String strStringA = new String("01234");
string strStringB= new String ("56789");
strStringA.concat(strStringB)   //"0123456"

7、其他数据转换为字符串

String 类中提供了静态方法 valueOf(), 用来把不同类型的简单数据转化为字符串。
声明格式如下:

public static String valueOf( boolean b);
public static String valueOf( char c);
public static String valueOf( char[] data);
public static String valueOf( char[] data, int offset, int count);
public static String valueOf( double d);
public static String valueOf( float f);
public static String valueOf( long l);
public static String valueOf(Object obj)

特别注意的是:
如果参数为 true,则返回一个等于 “true” 的字符串,否则返回一个等于 “false” 的字符串。
如果 参数是 null 则返回一个等于 “null”的字符串,否则返回obj.toString().
其他方法则返回一个新分配的字符串,其内容为相应类型参数的字符串表示。

System.out.println(String.valueOf(Math.PI));    //3.141592653589793

8、字符串转化为其他数据

1) 类 Integer, Long, Float 和 Double 中也提供了 valueOf(), 用于把一个字符串转化为对应的数字对象类型。声明格式如下:

public static Integer valueOf(String s) throws NumberFormatException
public static Long valueOf(String s) throws NumberFormatException
public static Float valueOf(String s) throws NumberFormatException
public static Double valueOf(String s) throws NumberFormatException

特别需要注意的是,若该String 不能作为相应数据类型对象的转化,则抛出异常。
用户可以调用 Integer, Long, Float 和 Double 类中的 valueOf()方法将字符串转化为相应的封装数据类型,进而转化为简单的数据类型。

同时 Boolean, Byte, Integer, Long, Float 和 Double 等类分别提供了静态方法:
public static parseDouble(String s);
public static parseInt(String s)
public static parseFloat(string s)
public static parseLong(String s)
public static parseBoolean(String s)
public static parseByte(String s)

String ints = "123";
int a = Integer.parseInt(ints);   //123
String ints="123.35";
float a = Integer.parseFloat(ints);  //123.45

猜你喜欢

转载自blog.csdn.net/daicooper/article/details/80786273