zoukankan      html  css  js  c++  java
  • Java中String类


    字符串:就是由多个字符组成的一串数据。也可以看成是一个字符数组。 /**String类的判断功能:String类的获取功能:字符串的转换功能:*/
    通过查看API,我们可以知道
    A:字符串字面值"abc"也可以看成是一个字符串对象。
    B:字符串是常量,一旦被赋值,就不能被改变。
    构造方法:
    /**public String():空构造
    public String(byte[] bytes):把字节数组转成字符串
    public String(byte[] byte,int index,int length):把字节数组的一部分转成字符串
    public String(char[] value):把字符数组转成字符串
    public String(char[] value,int index,int count):把字符数组的一部分转成字符串
    public String(String original):把字符串常量值转成字符串*/

    字符串的方法:
    public int length():返回此字符串的长度。
    public class StringDemo {
    public static void main(String[] args) {
    //public String():空构造
    String s1 = new String();
    System.out.println(s1);
    System.out.println("s1.length():"+s1.length()); //0
    System.out.println();

    //public String(byte[] bytes):把字节数组组成字符串
    byte[] bys = {97,98,99,100,101};
    String s2 = new String(bys);
    System.out.println(s2);//abcde
    System.out.println("s2.length():"+s2.length());//5

    //public String(byte[] byte,int index,int length):把字节数组的一部分转成字符串
    byte[] bys = {97,98,99,100,101};
    String s3 = new String(bys,1,3);
    System.out.println(s3);//bcd
    System.out.println("s3.length():"+s3.length());//3

    //public String(char[] value):把字符数组转成字符串
    char[] bys = { 's', 'd', 'f', 'w', '爱', '你' };
    String s4 = new String(bys);
    System.out.println(s4);//sdfw爱你
    System.out.println("s4.length():" + s4.length());//6

    //public String(char[] value,int index,int count):把字符数组的一部分转成字符串
    char[] bys = {'a','s','d','f','g','爱','你'};
    String s5 = new String(bys,2,5);
    System.out.println(s5);//dfg爱
    System.out.println("s5.length():"+s5.length());//4

    //public String(String original):把字符串常量值转成字符串
    String s6 = new String("abcde");
    System.out.println(s6);//abcde
    System.out.println(s6.length());//5

    }
    }
    字符串特点:一旦被赋值,就不能改变。
    public class StringDemo {
    public static void main(String[] args) {
    String s = "hello";
    s += "world";
    System.out.println("s:" + s); //helloworld
    解释:
    String s = "hello";
    创建String类型s 会去方法区字符串常量池中找有没有hello 发现没有 于是
    自动创建一个
    s += "world"
    先去字符串常量池找没有,自建一个,然后+=就是把字符串常量"hello"和"world"连到一起创建一个helloworld的空间赋值给s 输出
    正体现了一旦赋值无法改变
    //字符串直接赋值的方式是先到字符串常量池里面去找,如果有直接返回,没有,就创建并返回。
    }
    }

    String字面值对象和构造方法创建对象的区别
    面试题:
    String s = new String("hello"); String s = "hello"; 这两个有什么区别

    public static void main(String[] args) {
    String s1 = new String("hello");
    String s2 = "hello";

    System.out.println(s1 == s2);//flase
    System.out.println(s1.equals(s2));//true

    解释为什么第二个会是true:首先String s1 = new String("hello"); 会在方法区的字符串常量区创建一个hello空间,赋值给s1,然后s2创建的时候会直接找到字符串常量区中的hello 所以地址相同 equals默认比较地址值 为true
    所以 答案:有。前者会创建两个对象,后者创建一个对象。 String s1 = new String();会在栈内存创建String内存 字符串常量区会创建一个hello 这一共是两个对象。
    而String s2 = "hello" 也会在栈中创建一个String s2对象
    }

    ==:比较引用类型比较的是地址值是否相同
    equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。

    //看程序写结果
    //字符串如果是变量相加,先开空间,在拼接
    //字符串如果是常量相加,先相加,然后再常量池找,如果有就直接返回,否则,就创建。
    题1:
    public static void main(String[] args) {
    String s1 = "hello";
    String s2 = "world";
    String s3 = "helloworld";
    System.out.println(s3 == s1+s2); //false
    System.out.println(s3.equals((s1 + s2))); //true
    System.out.println(s3 == "hello" + "world"); //true
    System.out.println(s3.equals("hello" + "world")); //true
    }
    题2:
    public static void main(String[] args) {
    String s1 = new String("hello");
    String s2 = new String("hello");
    System.out.println(s1 == s2); //false
    System.out.println(s1.equals(s2)); //true

    String s3 = new String("hello");
    String s4 = "hello";
    System.out.println(s3 == s4); //false
    System.out.println(s3.equals(s4)); //true

    String s5 = "hello";
    String s6 = "hello";
    System.out.println(s5 == s6); //true //因为都只在栈内存中创建一个对象,所以都相等
    System.out.println(s5.equals(s6)); //true
    }

    String类的判断功能:
    /**boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
    boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
    boolean contains(String str):判断大写字符串中是否包含小字符串
    boolean startsWith(String str):判断字符串是否以某个指定的字符串开头,区分大小写
    boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾,区分大小写
    boolean isEmpty():判断字符串是否为空*/

    注意:
    字符串内容为空和字符串对象为空不同。
    String s = "";
    String s = null;

    public class StringDemo {
    public static void main(String[] args) {
    //创建字符串对象
    String s1 = "helloworld";
    String s2 = "helloworld";
    String s3 = "Helloworld";

    //boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
    System.out.println("equals:" + s1.equals(s2)); //true
    System.out.println("equals:" + s1.equals(s3)); //false
    //boolean equalsIgnoreCase(String str):比价字符串的内容是否相同,忽略大小写
    System.out.println("equalsIgnoreCase:" + s1.equalsIgnoreCase(s2)); //true
    System.out.println("equalsIgnoreCase:" + s1.equalsIgnoreCase(s3)); //true
    //boolean contains(String str):判断大写字符串中是否包含小字符串,区分大小写
    System.out.println("contains:" + s1.contains("hello")); //true
    System.out.println("contains:" + s1.contains("hw")); //false
    System.out.println("contains:" + s1.contains("nta")); //true
    //boolean starsWith(String str):判断字符串是否以某个指定的字符串开头,区分大小写
    System.out.println("startsWith:" +s1.startsWith("h")); //true
    System.out.println("startsWith:" +s1.startsWith("hello")); //true
    System.out.println("startsWith:" +s1.startsWith("Hello")); //false
    //boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾,区分大小写
    System.out.println("endsWith:" + s1.endsWith("world")); //true
    System.out.println("endsWith:" + s1.endsWith("worlD")); //false
    //boolean isEmpty():判断字符串是否为空
    System.out.println("isEmpty():" +s1.isEmpty()); //false
    String s4 = "";
    String s5 = null;
    System.out.println("isEmpty():" +s4.isEmpty()); //false
    //NullPointerException
    //s5对象都不存在,所以不能调用方法,空指针异常
    System.out.println("isEmpty():" +s5.isEmpty()); // true
    }
    }
    模拟用户登录案例:
    public static void main(String[] args) {
    String username = "admin";
    String password = "158428";

    for (int x = 0; x < 3; x++) {
    Scanner a = new Scanner(System.in);
    System.out.println("请输入您的账号");

    String name = a.nextLine();
    System.out.println("请输入您的密码");
    String pasd = a.nextLine();
    if (name.equals(username) && pasd.equals(password)) {
    System.out.println("登录成功");
    break;
    } else {
    if((2-x) == 0){
    System.out.println("账号被锁定");
    }else {
    System.out.println("登录失败,你还有"+(2-x)+"次机会");
    }
    }
    }

    }

    String类的获取功能:
    /**int length():获取字符串的长度。
    char charAt(int index):获取指定索引位置的字符
    int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
    为什么这里是int类型,而不是char类型?
    原因是:'a'和97其实都可以代表'a'
    int indexOf(String str):返回指定字符串在次字符串中第一次出现处的索引。
    int indexOf(int ch,int fromIndex):返回指定字符在此字符中从指定位置后第一次出现处的索引。
    int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
    String substring(int start):从指定位置开始截取字符串,默认到末尾。
    String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。*/

    public static void main(String[] args) {
    String s1 = "helloworld";

    // int length():获取字符串的长度。
    System.out.println(a.length());// 10

    // char charAt(int index):获取指定索引位置的字符
    System.out.println(a.charAt(5));// w

    // int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
    System.out.println(a.indexOf('w'));// 5

    // int indexOf(int ch):返回指定字符串在此字符串中第一次出现处的索引。
    System.out.println(a.indexOf("wo"));// 5

    // int indexOf(int ch,int fromIndex):返回指定字符在此字符中从指定位置后第一次出现处的索引。
    System.out.println(a.indexOf('l', 4));// 8

    // int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
    System.out.println(a.indexOf("owo", 4));// 4

    // String substring(int start):从指定位置开始截取字符串,默认到末尾。包含start索引本身
    System.out.println(a.substring(2));// lloworld

    // String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。包含start,不包含end,包左不包右。
    System.out.println(a.substring(2, 6));// llow
    }

    题:输入字符串 查询大小写字母和数字的个数:
    public static void main(String[] args) {
    String zfc;

    int bigCount = 0;
    int smallCount = 0;
    int numberCount = 0;

    Scanner s = new Scanner(System.in);
    System.out.println("请输入需要测试的字符串");
    zfc = s.nextLine();

    for (int x = 0; x < zfc.length(); x++) {
    char ch = zfc.charAt(x);

    if (ch >= 'a' && ch <= 'z') {
    smallCount++;
    } else if (ch > 'A' && ch <= 'z') {
    bigCount++;
    } else if (ch >= '0' && ch <= '9') {
    numberCount++;
    }
    }

    System.out.println("大写字母:" + bigCount);
    System.out.println("小写字母:" + smallCount);
    System.out.println("数字:" + numberCount);
    }

    字符串的转换功能:
    /**byte[] getBytes():把字符串转换成字节数组
    char[] toCharArray():把字符串转换为字符数组。
    static String calueOf(char[] chs):把字符数组转成字符串。
    static String calueOf(int i):把int类型的数据转成字符串。
    注意:String类的valueOf方法可以把任意类型的数据转成字符串。
    String toLowerCase():把字符串转成小写。
    String toUpperCase():把字符串转成大写。
    String concat(String str):把字符串拼接。*/

    public static void main(String[] args) {
    // 定义一个字符串对象
    String s = "Hello";
    // byte[] getBytes():把字符串转换成字节数组
    byte[] bys = s.getBytes();
    for (int x = 0; x < bys.length; x++) {
    System.out.println(bys[x]);//72 101 108 108 111
    }
    // char[] toCharArray():把字符串转换为字符数组。
    char[] chs = s.toCharArray();
    for (int x = 0; x < chs.length; x++) {
    System.out.println(chs[x]);//Hello
    }
    // static String calueOf(char[] chs):把字符数组转成字符串。
    String ss = String.valueOf(chs);
    System.out.println(ss);//Hello

    // static String calueOf(int i):把int类型的数据转成字符串。
    int i = 100;
    String sss = String.valueOf(i);
    System.out.println(sss);//100

    // String toLowerCase():把字符串转成小写。
    String ssss = "Hello";
    System.out.println(ssss.toLowerCase());//hello

    // String toUpperCase():把字符串转成大写。
    String sssss = "Hello";
    System.out.println(sssss.toUpperCase());//HELLO

    // String concat(String str):把字符串拼接。
    String s1 = "Hello";
    String s2 = "World";
    System.out.println(s1.concat(s2));//HelloWorld
    String s3 = s1 + s2;
    System.out.println(s3);//HelloWorld
    }

    下面这个练习题运用到了获取和转换功能:
    题目:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)
    String s = "helloWORLD";

    String s1 = s.substring(0, 1);

    String s2 = s.substring(1);

    String s3 = s1.toUpperCase();

    String s4 = s2.toLowerCase();

    String s5 = s3.concat(s4);

    System.out.println(s5);//Helloworld

    链式编程:
    String result = s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase());
    System.out.println(result);

    String类的其他功能:

    //替换功能:
    //String replace(char old,char new)
    //String replace(String old,String new)

    //去除字符串两空格
    //String trim()

    //按字典顺序比较两个字符串
    //int compareTo(String str)
    //int compareToIgnoreCase(String str)

    替换实例:
    String s1 = "helloworld";
    String s2 = s1.replace('l','k');
    String s3 = s1.replace("owo","ak47");
    System.out.println(s1);//helloworld
    System.out.println(s2);//hekkoworkd
    System.out.println(s3);//hellak47rld

    去除字符串两空格
    String s4 = " hello world ";
    String s5 = s4.trim();
    System.out.println("s4:" + s4 + "---");//s4: hello world ---
    System.out.println("s5:" + s5 + "---");//s5:hello world--- //达到了去除字符串两端空格效果,中间不去除

    按字典顺序比较两个字符串
    String s6 = "hello";
    String s7 = "hello";
    String s8 = "abc";
    String s9 = "xyz";
    System.out.println(s6.compareTo(s7));//0 比较s6第一个字符对应s7第一个字符ascii码表中值的差,第一个相同比后面的 所有字符都一样就是0
    System.out.println(s6.compareTo(s8));//7 同理 h - a = 7
    System.out.println(s6.compareTo(s9));//-16
    //有一个特殊的
    String s5 = "hel";
    System.out.println(s6.compareTo(s5));//2
    那为什么这里是2呢?
    如果两个字符串前面都一样,第一个比较第二个,多余的每个算1,也就是比较长度差。

    //把int数组拼接字符串的案例
    需求:把数组中的数据按照指定格式拼接成一个字符串
    举例:
    int[] arr = {1,2,3};
    输出结果:
    "[1,2,3]"
    分析:
    A:定义一个字符串对象,只不过内容为空
    B:先把字符串拼接一个"["
    C:遍历int数组,得到每一个元素
    D:先判断该元素是否为最后一个
    是:就直接拼接元素和"]"
    不是:就拼接元素和逗号以及空格
    E:输出拼接后的字符串
    //代码:
    public static void main(String[] args) {
    //创建空数组
    int[] arr = { 1, 2, 3 };
    // 定义一个字符串对象,只不过内容为空
    String s = "";
    //先把字符串拼接一个"["
    s += "[";
    //遍历int数组,得到每一个元素
    for (int x = 0; x < arr.length; x++) {
    //先判断该元素是否为最后一个
    if (x == arr.length - 1) {
    //是:直接拼接元素和"]"
    s += arr[x];
    s += "]";
    } else {
    //不是:就拼接元素和逗号以及空格
    s += arr[x];
    s += ", ";
    }
    }
    // 输出拼接后的字符串
    System.out.println("最终的字符串是:" + s);
    }
    //案例:
    字符串反转
    举例:键盘录入"abc"
    输出:"cba"

    分析:
    A:键盘录入一个字符串
    B:定义一个新字符串
    C:倒着遍历字符串,得到每一个字符
    a:length()和charAt()结合
    b:把字符串转成字符数组
    D:用新字符串把每一个字符拼接起来
    E:输出新串 ------------------------------------------(this is)

    public class Aaaa {

    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("请输入字符串:");
    String ff = sc.nextLine();

    String result = "";

    char[] arr = ff.toCharArray();

    for (int x = arr.length - 1; x >= 0; x--) {
    result += arr[x];
    }
    System.out.println("反转结果是:" + result);
    }
    }
    //改进为方法 实现:
    public class Aaaaa {

    public static String method(String s) {

    String result = "";

    char[] arr = s.toCharArray();

    for (int x = arr.length - 1; x >= 0; x--) {
    result += arr[x];
    }
    return result;
    }

    }

    //调用(测试类):
    import java.util.Scanner;

    public class Aaaa {

    public static void main(String[] args) {
    Scanner ss = new Scanner(System.in);
    System.out.println("请输入一个字符串:");
    String s = ss.nextLine();

    System.out.println("反转后的字符串为:" + Aaaaa.method(s));
    }
    }

  • 相关阅读:
    把特斯拉送上火星的程序员,马斯克!
    简练软考知识点整理-激励理论之成就动机理论
    简练软考知识点整理-激励理论之期望理论
    简练软考知识点整理-激励理论之XY理论
    简练软考知识点整理-激励理论之赫兹伯格双因素理论
    2017白领年终奖调查出炉,程序员扎心了!
    简练软考知识点整理-项目人力资源管理之马斯洛需要层次理论
    fsck获取文件的block信息和位置信息
    Snapshots常用命令
    Inceptor Parse error [Error 1110] line 102,24 SQL问题
  • 原文地址:https://www.cnblogs.com/lszbk/p/12318420.html
Copyright © 2011-2022 走看看