String类之详解(三)

 

String类之详解(三)

7、String中转换功能的函数

 byte[] getBytes()
          使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
char[] toCharArray()
          将此字符串转换为一个新的字符数组。
static String valueOf(char[] data)
          返回 char 数组参数的字符串表示形式。
static String valueOf(int i)
          返回 int 参数的字符串表示形式。

注意:String类的valueOf方法可以把任意类型的数据转成字符串

 String toLowerCase()
          使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
 String toUpperCase()
          使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
 String concat(String str)
          将指定字符串连接到此字符串的结尾。

1.getBytes()

    public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }
通过码表将字符串转换成字节数组,gbk码表一个中文代表两个字节,gbk码表特点,中文的第一个字节肯定是负数
                String s3 = "琲";
		byte[] arr3 = s3.getBytes();
		for (int i = 0; i < arr3.length; i++) {
			System.out.print(arr3[i] + " ");
		}

//-84 105

2.toCharArray()

public char[] toCharArray() {
        // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

新建字符数组,通过System的arraycopy()函数,将String类中底层的字符数组复制到新数组中。而arraycopy()函数为本地函数,该复制为深复制。

3.valueOf(char[] data)

public static String valueOf(char data[]) {
        return new String(data);
    }

通过构造方法生成新字符串。

还有一个方法名为copyValueOf()对于字符数组的操作和valueOf()一模一样,不知道为什么。

4.valueOf(int i)

public static String valueOf(int i) {
        return Integer.toString(i);
    }

通过包装类的toString()方法生成新字符串,其它包装类相同。

5.concat(String str)

public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        //新建字符数组,长度为两字符串总长,将原字符串字符复制到前半段
        char buf[] = Arrays.copyOf(value, len + otherLen);
        //从len长度之后,将目标字符串复制到新数组
        str.getChars(buf, len);
        return new String(buf, true);
    }
public static char[] copyOf(char[] original, int newLength) {
        char[] copy = new char[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
void getChars(char dst[], int dstBegin) {
        System.arraycopy(value, 0, dst, dstBegin, value.length);
    }
concat()与“+”的区别:
1、用+拼接字符串更强大,可以用字符串与任意类型相加
2、concat方法调用的和传入的都必须是字符串

8.转换功能函数应用

(1)把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)

//链式编程
public static void main(String[] args) {
		String s = "woaiHEImaniaima";
		String s2 = s.substring(0, 1).toUpperCase().concat(s.substring(1).toLowerCase());
		System.out.println(s2);
	}

9.String中替换功能的函数

 String replace(char oldChar, char newChar)
          返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
 String replace(CharSequence target, CharSequence replacement)
          使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。
 String trim()
          返回字符串的副本,忽略前导空白和尾部
 int compareTo(String anotherString)
          按字典顺序比较两个字符串。
 int compareToIgnoreCase(String str)
          按字典顺序比较两个字符串,不考虑大小写。

(1) replace(char old ,char new)

public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */

            //寻找字符串中第一个为oldChar的字符
            while (++i < len) {
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                //新建字符数组
                char buf[] = new char[len];
                //将i之前的字符复制到新数组中
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];
                }
                //将i之后的old替换为new
                while (i < len) {
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                //返回新字符串
                return new String(buf, true);
            }
        }
        //如果old==new,返回该字符串本身
        return this;
    }

通过上述代码可知:经过该方法后获得的字符串为新字符串(old ! = new),所以在使用该方法时要注意进行赋值操作!

(2)trim()

public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        //寻找第一个不是‘ ’的字符的索引值
        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        //寻找最后一个不是‘ ’的字符的索引值
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        //截取字符串并返回,如无空格,返回原有字符串
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }

(3)compareTo(String anotherString)

public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            //返回第一个不相等的字符的码表中的差值
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        //如果两字符拥有的字符均相等,则返回两字符串长度差值,为0时,两字符串相等
        return len1 - len2;

(4)compareToIgnoreCase(String str)

    public int compareToIgnoreCase(String str) {
        return CASE_INSENSITIVE_ORDER.compare(this, str);
    }

 内部实现:

public int compare(String s1, String s2) {
            int n1 = s1.length();
            int n2 = s2.length();
            int min = Math.min(n1, n2);
            for (int i = 0; i < min; i++) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(i);
                if (c1 != c2) {
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    if (c1 != c2) {
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        if (c1 != c2) {
                            // No overflow because of numeric promotion
                            return c1 - c2;
                        }
                    }
                }
            }
            return n1 - n2;
        }

与上述原理基本相同, 可自行阅读! 

String s1 = "a";
		String s2 = "aaaa";
		
		int num = s1.compareTo(s2);				//按照码表值比较
		System.out.println(num);
		
		String s3 = "黑";
		String s4 = "马";
		int num2 = s3.compareTo(s4);
		System.out.println('黑' + 0);			//查找的是unicode码表值
		System.out.println('马' + 0);
		System.out.println(num2);
		
		String s5 = "heima";
		String s6 = "HEIMA";
		int num3 = s5.compareTo(s6);
		System.out.println(num3);
		
		int num4 = s5.compareToIgnoreCase(s6);
		System.out.println(num4);

/*
-3
40657
39532
1125
32
0
*/

10.字符串应用

统计大串中小串出现的次数

public static void main(String[] args) {
		//定义大串
		String max = "aaahdiasfjkaaaihfdsiaundaahiudhsauinaaandsjabhaaa";
		//定义小串
		String min = "aaa";
		
		//定义计数器变量
		int count = 0;
		//定义索引
		int index = 0;
		//定义循环,判断小串是否在大串中出现
		while((index = max.indexOf(min)) != -1) {
			count++;									//计数器自增
			max = max.substring(index + min.length());
		}
		
		System.out.println(count);
	}

主体实现:

while((index = max.indexOf(min)) != -1) {
			count++;									//计数器自增
			max = max.substring(index + min.length());
		}

扫描二维码关注公众号,回复: 4220103 查看本文章
while((index = (max.indexOf(min,index))) != -1) {
			count++;									//计数器自增
			index+=min.length();
		}

猜你喜欢

转载自blog.csdn.net/qq_40298054/article/details/84187184