0
点赞
收藏
分享

微信扫一扫

String用法

小磊z 2022-03-30 阅读 47
java

字符串(String)是由数字、字母、下划线组成的一串字符。

字符串的创建:

1.创建字符串的简单方式:

String str = "创建字符串";

2.用构造函数创建字符串:

String str = new String("创建字符串");

字符串的连接:

1.使用concat方法:将指定字符串连接到该字符串的末尾。

String n = "he";
String a = n.concat("llo");   //a为hello

2.使用操作符 "+" 。

String s = "he" + "llo" ;  //s为hello

String常用方法:

1. 返回指定索引的char值:索引范围为 0 ~ lengh-1

charAt(int  index); 

charAt(int index);
String s = "hello world!";
charAt(s.charAt(3)); //返回值为第4个字符 l

2.拆分字符串:根据匹配的正则表达式拆分字符串,拆分后的字符串被自动存放在String类型的数组中。

split(int regex); 

String str = "hello-world-!";
       String[] arr = str.split("-");  //用String类型的数组arr存放拆分后的字符
       for(String s : arr){            //增强for循环遍历arr数组并输出
            System.out.println(s);    
       }
//输出结果为hello
//         world
//         !

3.截取字符串

索引范围 0~lengh-1

substring(int beginIndex) 返回一个从beginIndex到末尾的字符串;

substring(int beginIndex , int endIndex) 返回一个从 beginIndex 开始,以endIndex(不包括)前一个结束的字符串。

String str = "hello";
str.substring(2);  //返回 llo
str.substring(2,4);  //返回 ll

字符串转换为字符数组:

toCharArray();

String str = "hello";
            char[] char_arry =str.toCharArray();
            for (int i = 0; i < str.length(); i++) {
                System.out.println(char_arry[i]);
            }
/*
输出为:
h
e
l
l
o
*/

数组转换为一个字符串:

通过for循环,用 StringBuffer.append 方法在字符串后添加字符

String[] arr = { "hello", "world", "!" };
      StringBuffer str = new StringBuffer();
      for (String s : arr) {
         str.append(s+" ");    // 用 StringBuffer.append 方法在字符串后添加字符
      }
      System.out.println(str); //hello world !

举报

相关推荐

0 条评论