Java中String的几个常用构造方法

ゞ 浴缸里的玫瑰 2023-02-25 13:24 101阅读 0赞

关于String类常用的构造方法:

1、String s = “”; (这是用的最多的)

2、String s = new String(“”);

3、String s = new String(byte[] bytes);

4、String s = new String(byte[] bytes, int offset, int length);

5、String s = new String(char[] chars);

6、String s = new String(char[] chars, int offset, int length);


测试代码:

  1. public class Test03 {
  2. public static void main(String[] args) {
  3. //用的最多的字符串初始化是
  4. String s1 = "hello world";
  5. System.out.println(s1); //输出:hello world
  6. //new String(String str)
  7. String s2 = new String("good job");
  8. System.out.println(s2); //输出:good job
  9. //new String(byte[] bytes)
  10. byte[] bytes = { 97, 98, 99, 100}; //48-57:0-9 65-90:A-Z 97-122:a-z
  11. String s3 = new String(bytes);
  12. System.out.println(s3); //输出:abcd
  13. //new String(byte[] bytes, int offset, int length) 其中offset是数组的起始下标,length是长度
  14. String s4 = new String(bytes, 1, 3);
  15. System.out.println(s4); //输出:bcd
  16. //new String(char[] chars)
  17. char[] chars = { 's', 't', 'u', 'd', 'e', 'n', 't'};
  18. String s5 = new String(chars);
  19. System.out.println(s5); //输出:student
  20. //new String(char[] chars, int offset, int length)
  21. char[] chars1 = { '我', '是', '中', '国', '人'};
  22. String s6 = new String(chars1, 2, 3);
  23. System.out.println(s6); //输出:中国人
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,101人围观)

还没有评论,来说两句吧...

相关阅读

    相关 清除浮动方法

    浮动是我们在平时布局时经常用到的一种方式,不过也因此而带来一些问题,比如浮动会造成浮动元素的父元素高度“坍塌”的问题,那么这篇文章就来介绍几种常用的解决由浮动带来的一些问题。