花几千上万学习Java,真没必要!(十八)

字符串:

测试代码1:

java 复制代码
package testclass.com;
import java.nio.charset.StandardCharsets;  

public class StringConstructorDemo {  
    public static void main(String[] args) {  
        // 使用空字符串创建String对象  
        String emptyString = new String();  
        System.out.println("Empty String: " + emptyString);  
  
        // 使用字符数组创建String对象  
        char[] charArray = {'J', 'a', 'v', 'a'};  
        String stringFromCharArray = new String(charArray);  
        System.out.println("String from CharArray: " + stringFromCharArray);  
  
        // 使用字符串字面量
        String stringLiteral = "Hello, World!";  
        System.out.println("String Literal: " + stringLiteral);  
  
        // 使用字符串的子集创建String对象  
        String originalString = "Hello, Java!";  
        String substring = new String(originalString.toCharArray(), 7, 4); // 从索引7开始,长度为4("Java")  
        System.out.println("Substring: " + substring);  
  
        // 使用字节数组和编码创建String对象  
        byte[] byteArray = {72, 101, 108, 108, 111}; // ASCII码对应的"Hello"  
        String stringFromByteArray = new String(byteArray, StandardCharsets.UTF_8);  
        System.out.println("String from ByteArray: " + stringFromByteArray);  
  
        // 使用StringBuilder创建String对象  
        StringBuilder sb = new StringBuilder();  
        sb.append("Goodbye, ");  
        sb.append("World!");  
        String stringFromStringBuilder = sb.toString();  
        System.out.println("String from StringBuilder: " + stringFromStringBuilder);  
    }  
}

运行结果如下:

测试代码2:

java 复制代码
package testclass.com;
public class StringDemo {  
    public static void main(String[] args) {  
        // 字符串的不可变性  
        String originalString = "Hello";  
        String modifiedString = originalString + " World!";  
        System.out.println("Original: " + originalString);  
        System.out.println("Modified: " + modifiedString);  
        System.out.println("Original still the same? " + (originalString == "Hello"));
  
        // 更好的证明不可变性的方式 
        System.out.println("Original hash code before modification: " + originalString.hashCode());  
        System.out.println("Modified hash code: " + modifiedString.hashCode()); // 不同的hashCode表明它们是不同的对象  
  
        // 字符串常量池  
        String fromLiteral1 = "Hello";  
        String fromLiteral2 = "Hello";  
        String fromNew = new String("Hello");  
  
        System.out.println(fromLiteral1 == fromLiteral2); // true,指向常量池中的同一个对象  
        System.out.println(fromLiteral1 == fromNew); // false,fromNew在堆上创建了新的对象  
  
        // 丰富的方法库  
        String example = "Hello, World! Java is awesome.";  
  
        // 查找  
        int index = example.indexOf("Java");  
        System.out.println("Index of 'Java': " + index);  
  
        // 替换  
        String replaced = example.replace("World", "Everyone");  
        System.out.println("Replaced string: " + replaced);  
  
        // 截取子字符串  
        String substring = example.substring(7, 12); // "World"  
        System.out.println("Substring: " + substring);  
  
        // 忽略大小写比较  
        boolean isIgnoreCaseEqual = example.equalsIgnoreCase("hello, world! java is awesome.");  
        System.out.println("Ignore case equal? " + isIgnoreCaseEqual);  
  
        // 使用StringBuilder说明字符串的不可变性
        StringBuilder sb = new StringBuilder("Hello");  
        sb.append(" Java");  
        String builtString = sb.toString();  
        System.out.println("Built string: " + builtString);  
    }  
}

运行结果如下:

测试代码3:字符串常见的处理方法

java 复制代码
package testclass.com;
public class StringUtils {  
	  
    // 字符串比较(内容)  
    public static boolean equalsIgnoreCase(String str1, String str2) {  
        return str1 != null && str2 != null && str1.equalsIgnoreCase(str2);  
    }  
  
    // 统计字符次数  
    public static int countChar(String str, char ch) {  
        int count = 0;  
        for (int i = 0; i < str.length(); i++) {  
            if (str.charAt(i) == ch) {  
                count++;  
            }  
        }  
        return count;  
    }  
  
    // 字符串拼接  
    public static String concatStrings(String... strings) {  
        StringBuilder sb = new StringBuilder();  
        for (String str : strings) {  
            sb.append(str);  
        }  
        return sb.toString();  
    }  
  
    // 字符串反转  
    public static String reverseString(String str) {  
        return new StringBuilder(str).reverse().toString();  
    }  
  
    // 字符串截取  
    public static String substring(String str, int beginIndex, int endIndex) {  
        return str.substring(beginIndex, endIndex);  
    }  
}
java 复制代码
package testclass.com;
public class StringOperationsDemo {  
    public static void main(String[] args) {  
        String str1 = "Hello, World!";  
        String str2 = "hello, world!";  
  
        // 字符串比较(内容)  
        System.out.println("str1 equalsIgnoreCase str2: " + StringUtils.equalsIgnoreCase(str1, str2));  
  
        // 统计字符次数  
        System.out.println("Count of 'o' in str1: " + StringUtils.countChar(str1, 'o'));  
  
        // 字符串拼接  
        String str3 = "Java ";  
        String str4 = "is fun!";  
        System.out.println("Concatenated string: " + StringUtils.concatStrings(str3, str4));  
  
        // 字符串反转  
        System.out.println("Reversed string: " + StringUtils.reverseString(str1));  
  
        // 字符串截取  
        System.out.println("Substring from 7 to 12 (inclusive): " + StringUtils.substring(str1, 7, 12));  
    }  
}

运行结果如下:

测试代码4:实现一个简单的订单处理类

java 复制代码
package testclass.com;
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
public class OrderProcessor {  
  
    // 订单号格式为:YYYYMMDDHHMMSSNNN,其中NNN是序列号(001-999)  
    private static final String ORDER_NUMBER_PATTERN = "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{3})";  
    private static final Pattern ORDER_PATTERN = Pattern.compile(ORDER_NUMBER_PATTERN);  
  
    // 验证并解析订单号  
    public static OrderInfo parseAndValidateOrderNumber(String orderNumber) {  
        if (orderNumber == null || orderNumber.isEmpty()) {  
            return null; // 订单号为空或null,返回null  
        }  
  
        Matcher matcher = ORDER_PATTERN.matcher(orderNumber);  
        if (!matcher.matches()) {  
            return null; // 订单号格式不正确,返回null  
        }  
  
        // 解析订单号  
        String year = matcher.group(1);  
        String month = matcher.group(2);  
        String day = matcher.group(3);  
        String hour = matcher.group(4);  
        String minute = matcher.group(5);  
        String second = matcher.group(6);  
        String sequence = matcher.group(7);  
  
        // 验证序列号是否有效(假设序列号为001-999)  
        if (Integer.parseInt(sequence) < 1 || Integer.parseInt(sequence) > 999) {  
            return null; // 序列号无效,返回null  
        }  
  
        // 构造日期时间对象  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
        try {  
            Date orderDate = sdf.parse(year + month + day + hour + minute + second);  
            return new OrderInfo(orderDate, Integer.parseInt(sequence));  
        } catch (ParseException e) {  
            // 理论上这里不会抛出异常,格式已经通过正则表达式验证  
            return null; // 如果抛出异常,可能是日期格式字符串错误,返回null  
        }  
    }  
  
    // 订单信息类  
    public static class OrderInfo {  
        private Date orderDate;  
        private int sequence;  
  
        public OrderInfo(Date orderDate, int sequence) {  
            this.orderDate = orderDate;  
            this.sequence = sequence;  
        }  
  

  
        @Override  
        public String toString() {  
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            return "OrderInfo{" +  
                    "orderDate='" + sdf.format(orderDate) + '\'' +  
                    ", sequence=" + sequence +  
                    '}';  
        }  
    }  
  
    public static void main(String[] args) {  
        String orderNumber = "20230401123045123";  
        OrderInfo orderInfo = parseAndValidateOrderNumber(orderNumber);  
        if (orderInfo != null) {  
            System.out.println("Parsed Order Info: " + orderInfo);  
        } else {  
            System.out.println("Invalid order number.");  
        }  
    }  
}

运行结果如下:

相关推荐
eybk2 小时前
Pytorch+Mumu模拟器+萤石摄像头实现对小孩学习的监控
学习
6.942 小时前
Scala学习记录 递归调用 练习
开发语言·学习·scala
守护者1704 小时前
JAVA学习-练习试用Java实现“使用Arrays.toString方法将数组转换为字符串并打印出来”
java·学习
学会沉淀。4 小时前
Docker学习
java·开发语言·学习
Rinai_R4 小时前
计算机组成原理的学习笔记(7)-- 存储器·其二 容量扩展/多模块存储系统/外存/Cache/虚拟存储器
笔记·物联网·学习
吃着火锅x唱着歌4 小时前
PHP7内核剖析 学习笔记 第四章 内存管理(1)
android·笔记·学习
ragnwang4 小时前
C++ Eigen常见的高级用法 [学习笔记]
c++·笔记·学习
Web阿成6 小时前
3.学习webpack配置 尝试打包ts文件
前端·学习·webpack·typescript
雷神乐乐6 小时前
Spring学习(一)——Sping-XML
java·学习·spring