首页 > 技术文章 > String类使用

lyx1996 2017-06-10 11:29 原文

String类的使用

String类

String类在java.lang包中,java使用String类创建一个字符串变量,字符串变量属于对象。java把String类声明的final类,不能有类。String类对象创建后不能修改,由0或多个字符组成,包含在一对双引号之间。

String类对象的创建

字符串声明:String stringName;

字符串创建:stringName = new String(字符串常量); 或 stringName = 字符串常量;

String类常用方法

1、求字符串长度 length()

1 String str = new String("asdfzxc");
2 int strlength = str.length();//strlength = 7

2、求字符串某一位置字符 charAt(int index),字符串下标从0开始。

1 String str = new String("asdfzxc");
2 char ch = str.charAt(4);//ch = z

3、提取子串 substring(参数)

参数有常用的两种类型:
1)public String substring(int beginIndex)//该方法从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回。
2)public String substring(int beginIndex, int endIndex)//该方法从beginIndex位置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回。

 1 String str1 = new String("asdfzxc");
 2 String str2 = str1.substring(2);//str2 = "dfzxc"
 3 String str3 = str1.substring(2,5);//str3 = "dfz"

4、字符串比较 compareTo(String anotherString):对字符串内容按字典顺序进行大小比较,返回整数,若当前对象比参数大则返回正整数,反之返回负整数,相等返回0;equals(Object anotherObject):比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。

String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b = str1.compareTo(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d = str1.equalsIgnoreCase(str2);//d=true,和equals方法类似,忽略大小写

5、字符串分割 split(String regex)

String str1 = new String("a,b,c");
String[] str2 = str1.split(","); //{"a","b","c"}

具体解释:

课程实践

实践内容:模拟实现Linux下Sort -t : -k 2的功能。参考 Sort的实现。提交码云链接和代码运行截图。

Linux的Sort命令是将文件的每一行进行排序,从首字符开始比较ASCII码值,默认按升序输出。

sort(选项)(参数)

选项: -k:排序时,指定本域的开头和结尾;
    -n:依照数值的大小排序;
    -r:以相反的顺序来排序;
    t<分隔字符>:指定排序时所用的栏位分隔字符。
参数: 指定待排序的文件列表。

所以Sort -t : -k 2 指定分隔符为":",以第2列大小为准排列。

import java.util.*;

public class MySort1 {
public static void main(String [] args) {
    String [] toSort = {"aaa:10:1:1",
                        "ccc:30:3:4",
                        "bbb:50:4:5",
                        "ddd:20:5:3",
                        "eee:40:2:20"};

    System.out.println("Before sort:");
    for (String str: toSort)
          System.out.println(str);

    Arrays.sort(toSort);

    System.out.println("After sort:");
    for( String str : toSort)
         System.out.println(str);
  }
}

从上述代码可知,调用了Arrays的sort(array)方法,具体如下:

运行结果如下:

这段代码实现了将文档按照默认的排序方法,即从头到尾进行比较,然后升序排列。

为了实现Sort -t : -k 2 ,还需要将字符串分割和输出整合这两个部分补充上去,根据上述对split方法的学习,可使用split方法完成-t :这个部分的功能,具体如下:

Integer [] tmp = new Integer [toSort.length];
for(int i=0; i<tmp.length; i++)
tmp[i] = Integer.parseInt(toSort[i].split(":")[1]);

一个循环将文档中每一行的第2列数字保存到Integer数组中,这其中使用到了split分割方法,也使用了字符串转为整型的方法,这样就得到了每行的第2列数字。需要注意的是数组的下标从0开始,所以取第2列是数组的下标为1。

下一步就是整合输出,输出时从头至尾进行判定,若该行的第2个数的值和保存第2列数组i中的相同,则将这行输出,循环直至输出完成为止,具体代码为:
for(int i=0; i<tmp.length; i++)
for(int j=0; j<toSort.length; j++)
if(Integer.parseInt(toSort[j].split("

推荐阅读