String

2018-11-01  本文已影响10人  我把心事寄流年
String str = "abc";

相当于

char data[] = {'a', 'b', 'c'};
String str = new String(data);

String底层是靠字符数组实现的


无参构造

String str = new String();

通过字符数组构造

char chars[] = {'a', 'b', 'c'};
String str2 = new String(chars);

通过字节数组构造

byte bytes[] = { 97, 98, 99 };
String str3 = new String(bytes);

格式

str1.equals(str2)
str.length()
str.charAt(索引值)
str.indexOf("字符串")
str.substring(索引值)
str.substring(0, str.length()
str.substring(数字, 数字)
String str = "abcde";
char[] chs = str.toCharArray();
String str = "abcde";
byte[] bytes = str.getBytes();
String str = "it";
String replace = str.replace("it", "IT");
String str = "aa|bb|cc";
String[] strArray = s.split("|");

例题

定义一个方法,把数组{1,2,3}按照指定个格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。

public class StringTest1 {
    public static void main(String[] args) {
        //定义一个int类型的数组
        int[] arr = {1, 2, 3};
        //调用方法
        String s = arrayToString(arr);
        //输出结果
        System.out.println("s:" + s);
    }
/*
* 写方法实现把数组中的元素按照指定的格式拼接成一个字符串
* 两个明确:
* 返回值类型:String
* 参数列表:int[] arr
*/
public static String arrayToString(int[] arr) {
        // 创建字符串s
    String s = new String("[");
        // 遍历数组,并拼接字符串
    for (int x = 0; x < arr.length; x++) {
    if (x == arr.length ‐ 1) {
    s = s.concat(arr[x] + "]");
    } else {
    s = s.concat(arr[x] + "#");
    }
    }
    return s;
    }
}

键盘录入一个字符,统计字符串中大小写字母及数字字符个数

public class StringTest2 {
    public static void main(String[] args) {
        //键盘录入一个字符串数据
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串数据:");
        String s = sc.nextLine();
        //定义三个统计变量,初始化值都是0
        int bigCount = 0;
        int smallCount = 0;
        int numberCount = 0;
        //遍历字符串,得到每一个字符
        for(int x=0; x<s.length(); x++) {
            char ch = s.charAt(x);
            //拿字符进行判断
            if(ch>='A'&&ch<='Z') {
                bigCount++;
            }else if(ch>='a'&&ch<='z') {
                smallCount++;
            }else if(ch>='0'&&ch<='9') {
                numberCount++;
            }else {
            System.out.println("该字符"+ch+"非法");
        }
    }
            //输出结果
        System.out.println("大写字符:"+bigCount+"个");
        System.out.println("小写字符:"+smallCount+"个");
        System.out.println("数字字符:"+numberCount+"个");
    }
}

上一篇下一篇

猜你喜欢

热点阅读