String 字串

String 相關的題很常出現在面試題中,實際開發也經常用到,這裡總結一下 C++, Java, Python 中字串常用的方法。

Python

  1. s1 = str()
  2. # in python `''` and `""` are the same
  3. s2 = "shaunwei" # 'shaunwei'
  4. s2len = len(s2)
  5. # last 3 chars
  6. s2[-3:] # wei
  7. s2[5:8] # wei
  8. s3 = s2[:5] # shaun
  9. s3 += 'wei' # return 'shaunwei'
  10. # list in python is same as ArrayList in java
  11. s2list = list(s3)
  12. # string at index 4
  13. s2[4] # 'n'
  14. # find index at first
  15. s2.index('w') # return 5, if not found, throw ValueError
  16. s2.find('w') # return 5, if not found, return -1

在Python裡面,沒有StringBuffer 或者 StringBuilder。 但是在Python 裡面處理String本身就比較 cheap。

Java

  1. String s1 = new String();
  2. String s2 = "billryan";
  3. int s2Len = s2.length();
  4. s2.substring(4, 8); // return "ryan"
  5. StringBuilder s3 = new StringBuilder(s2.substring(4, 8));
  6. s3.append("bill");
  7. String s2New = s3.toString(); // return "ryanbill"
  8. // convert String to char array
  9. char[] s2Char = s2.toCharArray();
  10. // char at index 4
  11. char ch = s2.charAt(4); // return 'r'
  12. // find index at first
  13. int index = s2.indexOf('r'); // return 4. if not found, return -1

StringBuffer 與 StringBuilder, 前者保證執行緒安全(Thread Safety),後者不是,但單執行緒下效率高一些,一般使用 StringBuilder.