[关闭]
@liayun 2016-05-31T09:40:18.000000Z 字数 9213 阅读 1343

String

java基础


String

面试题,对于以下代码:

  1. String s1 = "abc"; // s1是一个类类型变量,"abc"是一个对象
  2. String s2 = new String("abc");

s1和s2有什么区别?
解:s1在内存中有一个对象,s2在内存中有两个对象。
对于以上代码,下面的代码会输出什么呢?

  1. System.out.println(s1==s2);
  2. System.out.println(s1.equals(s2));

会发现第一句输出false,第二句输出true,得出结论:String类复写了Object类中的equals(),该方法用于判断字符串是否相同。
String类是用于描述字符串事物的,那么它就提供了多个方法对字符串进行操作。常见的操作有哪些?

  1. public static void sop(Object obj) {
  2. System.out.println(obj);
  3. }
  4. public static void method_get() {
  5. String str = "abcdeakpf";
  6. // 长度
  7. sop(str.length());
  8. // 根据索引获取字符
  9. sop(str.charAt(4)); // 当访问到字符串中不存在的角标时,会发生StringIndexOutOfBoundsException。
  10. // 根据字符获取索引
  11. sop(str.indexOf('m', 3)); // 如果没有找到返回-1
  12. // 反向索引一个字符出现的位置
  13. sop(str.lastIndexOf("a"));
  14. }
  1. public static void sop(Object obj) {
  2. System.out.println(obj);
  3. }
  4. public static void method_is() {
  5. String str = "ArrayDemo.java";
  6. // 判断文件名称是否是以Array单词开头
  7. sop(str.startsWith("Array"));
  8. // 判断文件名称是否是.java文件
  9. sop(str.endsWith(".java"));
  10. // 判断文件名称是否包含Demo
  11. sop(str.contains("Demo"));
  12. }
  1. 3+""; // String.valueOf(3); int--->String
  1. public static void sop(Object obj) {
  2. System.out.println(obj);
  3. }
  4. public static void method_trans() {
  5. char[] arr = {'a','b','c','d','e','f'};
  6. String s = new String(arr,1,3);
  7. sop("s="+s);
  8. String s1 = "zxcvbnm";
  9. char[] chs = s1.toCharArray();
  10. for (int x = 0; x < chs.length; x++) {
  11. sop("chs="+chs[x]);
  12. }
  13. }

特殊:字符串和字节数组在转换过程中,是可以指定编码表的。

  1. public static void sop(Object obj) {
  2. System.out.println(obj);
  3. }
  4. public static void method_replace() {
  5. String s = "hello java";
  6. // String s1 = s.replace('q', 'n'); // 如果要替换的字符不存在,返回的还是原串
  7. String s1 = s.replace("java", "world");
  8. sop("s="+s);
  9. sop("s1="+s1);
  10. }
  1. public static void sop(Object obj) {
  2. System.out.println(obj);
  3. }
  4. public static void method_split() {
  5. String s = "zhangsan,lisi,wangwu";
  6. String[] arr = s.split(",");
  7. for (int x = 0; x < arr.length; x++) {
  8. sop(arr[x]);
  9. }
  10. }
  1. public static void sop(Object obj) {
  2. System.out.println(obj);
  3. }
  4. public static void method_sub() {
  5. String s = "abcdef";
  6. sop(s.substring(20)); //从指定位置开始到结尾,如果角标不存在,会出现字符串角标越界异常
  7. sop(s.substring(2,4));//包含头,不包含尾。获取整个字符串:s.substring(0, s.length());
  8. }
  1. public static void sop(Object obj) {
  2. System.out.println(obj);
  3. }
  4. public static void method_7() {
  5. String s = " Hello Java ";
  6. sop(s.toLowerCase());
  7. sop(s.toUpperCase());
  8. sop(s.trim());
  9. String s1 = "a1c";
  10. String s2 = "aaa";
  11. sop(s1.compareTo(s2));
  12. }

练习一、模拟一个trim()方法,去除字符串两端的空格。
解:
思路:

  1. 判断字符串第一个位置是否是空格,如果是继续向下判断,直到不是空格为止。结尾处判断空格也是如此
  2. 当开始和结尾都判断到不是空格时,就是要获取的字符串

代码如下:

  1. public class StringTest {
  2. public static void sop(String str) {
  3. System.out.println(str);
  4. }
  5. public static String myTrim(String str) {
  6. int start = 0, end = str.length()-1;
  7. while(start <= end && str.charAt(start) == ' ')
  8. start++;
  9. while(start <= end && str.charAt(end) == ' ')
  10. end--;
  11. return str.substring(start, end+1);
  12. }
  13. public static void main(String[] args) {
  14. String s = " ab cd ";
  15. sop("("+s+")");
  16. s = myTrim(s);
  17. sop("("+s+")");
  18. }
  19. }

练习二、将一个字符串进行反转。将字符串中指定的部分进行反转,"abcdefg"--->"abfedcg"
解:
思路:

  1. 将字符串变成数组
  2. 对数组反转
  3. 将数组变成字符串

代码如下:

  1. class StringTest {
  2. public static void sop(String str) {
  3. System.out.println(str);
  4. }
  5. public static String reverseString(String s, int start, int end) {
  6. // 字符串变成数组
  7. char[] chs = s.toCharArray();
  8. // 反转数组
  9. reverse(chs, start, end);
  10. // 将数组变成字符串
  11. return new String(chs);
  12. }
  13. public static String reverseString(String s) {
  14. return reverseString(s, 0, s.length());
  15. }
  16. private static void reverse(char[] arr, int x, int y) {
  17. for (int start = x, end = y - 1; start < end; start++, end--) {
  18. swap(arr, start, end);
  19. }
  20. }
  21. private static void swap(char[] arr, int x, int y) {
  22. char temp = arr[x];
  23. arr[x] = arr[y];
  24. arr[y] = temp;
  25. }
  26. public static void main(String[] args) {
  27. String s = "ab cd ";
  28. sop("("+s+")");
  29. sop("("+reverseString(s)+")");
  30. sop("("+reverseString(s, 0, 3)+")");
  31. }
  32. }

练习三、获取一个字符串在另一个字符串中出现的次数。例如,"kk"在"abkkcdkkefkkskk"出现的次数。
解:
思路:

  1. 定义一个计数器
  2. 获取"kk"第一次出现的位置
  3. 从第一次出现的位置后剩余的字符串中继续获取"kk"出现的位置,每获取一次就计数一次
  4. 当获取不到时,计数完成

代码如下:

  1. class StringTest2 {
  2. // 方式一
  3. public static int getSubCount(String str, String key) {
  4. int count = 0;
  5. int index = 0;
  6. while((index = str.indexOf(key)) != -1) {
  7. sop("str="+str);
  8. str = str.substring(index+key.length());
  9. count++;
  10. }
  11. return count;
  12. }
  13. // 方式二
  14. public static int getSubCount_2(String str, String key) {
  15. int count = 0;
  16. int index = 0;
  17. while ((index = str.indexOf(key, index)) != -1) {
  18. sop("index="+index);
  19. index = index + key.length();
  20. count++;
  21. }
  22. return count;
  23. }
  24. public static void main(String[] args) {
  25. String str = "kkabkkcdkkefkks";
  26. // sop("count======"+str.split("kk").length); // 字符串"kkabkkcdkkefkks"第一次按照"kk"分隔,会生成数组{"", "abkkcdkkefkks"},所以不建议使用split()方法
  27. sop("count="+getSubCount_2(str, "kk"));
  28. }
  29. public static void sop(String str) {
  30. System.out.println(str);
  31. }
  32. }

练习四、获取两个字符串中最大相同子串。例如,"abcwerthelloyuiodef"和"cvhellobnm"。
解:
思路:

  1. 将短的那个子串按照长度递减的方式获取到
  2. 将每获取到的子串去长串中判断是否包含,如果包含,已经找到

代码如下:

  1. class StringTest3 {
  2. public static String getMaxSubString(String s1, String s2) {
  3. String max = "", min = "";
  4. max = (s1.length() > s2.length()) ? s1 : s2;
  5. min = (max == s1) ? s2 : s1;
  6. // sop("max="+max+"...min="+min);
  7. for (int x = 0; x < min.length(); x++) {
  8. for (int y = 0, z = min.length() - x; z != min.length() + 1; y++, z++) {
  9. String temp = min.substring(y, z);
  10. // sop(temp);
  11. if(max.contains(temp))
  12. return temp;
  13. }
  14. }
  15. return "";
  16. }
  17. public static void main(String[] args) {
  18. String s1 = "abcwerthelloyuiodef";
  19. String s2 = "cvhellobnm";
  20. sop(getMaxSubString(s2, s1));
  21. }
  22. public static void sop(String str) {
  23. System.out.println(str);
  24. }
  25. }

StringBuffer

StringBuffer是字符串缓冲区,是一个容器。
特点:

  1. 长度可变化
  2. 可以直接操作多个数据类型
  3. 最终会通过toString()变成字符串

C(create) U(update) R(read) D(delete)

  1. public static void sop(String str) {
  2. System.out.println(str);
  3. }
  4. public static void method_add() {
  5. StringBuffer sb = new StringBuffer();
  6. sb.append("abc").append(true).append(34); // 方法调用链
  7. // StringBuffer sb1 = sb.append(34);
  8. // sop("sb==sb1:"+(sb == sb1));
  9. sb.insert(1, "qq");
  10. sop(sb.toString()); // aqqbctrue34
  11. // sop(sb1.toString());
  12. }
  1. public static void sop(String str) {
  2. System.out.println(str);
  3. }
  4. public static void method_delete() {
  5. StringBuffer sb = new StringBuffer("abcde");
  6. // sb.delete(1, 3);
  7. // 清空缓冲区
  8. // sb.delete(0, sb.length());
  9. // sb.delete(2, 3);
  10. sb.deleteCharAt(2);
  11. sop(sb.toString());
  12. }
  1. public static void sop(String str) {
  2. System.out.println(str);
  3. }
  4. public static void method_update() {
  5. StringBuffer sb = new StringBuffer("abcde");
  6. // sb.replace(1, 4, "java");
  7. sb.setCharAt(2, 'k');
  8. sop(sb.toString());
  9. }
  1. public static void main(String[] args) {
  2. StringBuffer sb = new StringBuffer("abcdef");
  3. char[] chs = new char[6];
  4. sb.getChars(1, 4, chs, 1);
  5. for (int x = 0; x < chs.length; x++) {
  6. sop("chs["+x+"]="+chs[x]+";");
  7. }
  8. }
  9. public static void sop(String str) {
  10. System.out.println(str);
  11. }

StringBuilder

JDK1.5版本之后,出现了StringBuilder
StringBuffer与StringBuilder的区别:

  1. StringBuffer是线程同步的
  2. StringBuilder是线程不同步的

StringBuilder的实例用于多个线程时是不安全的。如果需要这样的同步,则建议使用StringBuffer
注意:以后开发,建议使用StringBuilder。
升级三个因素:

  1. 提高效率
  2. 简化书写
  3. 提高安全

基本数据类型对象包装类

基本数据类型包装类的最常见作用:就是用于基本数据类型和字符串类型之间做转换。

  1. int a = Integer.parseInt("123");
  2. double b = Double.parseDouble("12.23");
  3. boolean b = Boolean.parseBoolean("true");
  4. // 还有一种形式:
  5. Integer i = new Integer("123");
  6. int num = i.intValue();
  1. // 将一个字符串转成整数
  2. int num = Integer.parseInt("a123");//NumberFormatException,必须传入数字格式的字符串
  3. System.out.println("num="+(num+4));
  1. System.out.println(Integer.toBinaryString(6));
  2. System.out.println(Integer.toBinaryString(-6));
  3. System.out.println(Integer.toHexString(60));
  1. int x = Integer.parseInt("3c", 16);
  2. sop("x="+x);

JDK1.5版本以后出现的新特性——装箱与拆箱
JDK1.5以后,简化了定义方式:如

  1. Integer x = new Integer("4");

可以直接写成:

  1. Integer x = 4; // 自动装箱

接着自动拆箱:

  1. x = x /*x.intValue()*/ + 2; // x+2:x进行了自动拆箱,变成了int类型,和2进行加法运算,再将和进行装箱赋给x

需要注意:在使用时,Integer x = null;上面的代码就会出现NullPointerException
面试题:以下代码会输出什么?

  1. class IntegerDemo {
  2. public static void sop(String str) {
  3. System.out.println(str);
  4. }
  5. public static void main(String[] args) {
  6. Integer m = 128;
  7. Integer n = 128;
  8. sop("m==n:"+(m==n));
  9. Integer a = 127;
  10. Integer b = 127;
  11. sop("a==b:"+(a==b));
  12. }
  13. }

答:falsetrue
解析:

  1. Integer m = 128;
  2. Integer n = 128;
  3. sop("m==n:"+(m==n)); // false,因为m和n指向了不同Integer对象,
  4. Integer a = 127;
  5. Integer b = 127;
  6. // 结果为true。因为a和b指向了同一个Integer对象,
  7. // 因为当数值在byte范围内时,对于新特性,如果该数值已经存在则不会再开辟新的空间
  8. sop("a==b:"+(a==b));
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注