Java学习笔记1——String类

一、String类
1、概念:字符串,是多个字符组成的一串数据。
位于java.lang包。
String类是一个被final修饰的类,表示不可被继承和修改。字符串的底层存储结构是char数组。

public final class String{...}

2、部分的构造函数
(1)空构造函数:String()
初始化一个新的空字符串对象

String str = new String();

(2)以String对象为参数:String(String string)

创建一个String类对象s,并将一个字符串str赋予新的String对象s

String s = new String("str");

(3)以字符数组为参数构造String:String(char value[])

创建一个String对象,将chs传入赋予s

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

(4)传入字符数组的子数组:String(char value[], int offset, int count)
将字符数组value(chs)从第offset位开始,传入长度为count的子数组构造成字符串s。

char[] chs = {'a','b','c','d','e'};
String s = new String(chs,1,3);

(5)传入整型int数组的子数组,构造对应字符的字符串:String(int[] codePoints, int offset, int count)
传入的数组为整型数组,将为转换为ASCII对应的字符。

int[] chs = {65,66,67,68,97,97};
String s = new String(chs,1,3);

(6)传入字节数组的子数组构建String对象:public String(byte bytes[], int offset, int length)
传入一个字节数组,从第offset个位置开始,取长度为length的子数组,构建一个新的字符串s。

byte[] chs = {1,2,3,4,5};
String s = new String(chs,1,3);

(7)传入字节数组构建String对象:public String(byte bytes[])
传入一个字符数组,构建一个新的字符串对象s。

byte[] chs = {1,2,3,4,5};
String s = new String(chs);

此构造方法是通过调用this(bytes, 0, bytes.length);即上述(6)的方法。

(8)传入字符数组,以指定编码构造字符串:public String(byte bytes[], int offset, int length, String charsetName)
指定编码传入字符数据构造字符串。

byte[] chs = {61,66,60,68,97,97};
String s = new String(chs,1,3,"GBK");

(9)传入StringBuffer并将转化为String:public String(StringBuffer buffer)
传入StringBuffer,调用toString()方法转化为字符串。

StringBuffer buffer = new StringBuffer("Hello World!");
String s = new String(buffer);

(10)传入StringBuilder并转化为String:public String(StringBuilder builder)
传入StringBuilder,调用toString()方法转化为字符串。与(9)同理。

StringBuilder builder = new StringBuilder("Hello World!");
String s = new String(builder);

3、常用方法
A:判断方法
(1)判断字符串的内容是否相同,区分大小写:public boolean equals(Object obj)
(2)判断字符串的内容是否相同,区分大小写:public boolean equalsIgnoreCase(String str)
(3)判断字符串对象是否包含指定的字符串:public boolean contains(String str)
(4)判断字符串对象是否以指定的字符串开始:public boolean startsWith(String str)
(5)判断字符串对象是否以指定的字符串结尾:public boolean endsWith(String str)
(6)判断字符串对象或数据是否为空:public boolean isEmpty()
(7)获取指定位置的字符的ACSII码:public int codePointAt(int index)
(8)获取指定位置的前一个字符的ACSII码:public int codePointBefore(int index)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 创建字符串对象  
        String str = "Hello World!";  

        // boolean equals(Object obj)
        // 判断字符串内容是否相同,区分大小写
        System.out.println(s.equals("Hello World!"));  
        System.out.println(s.equals("hello world!"));  
        System.out.println("--------------------");  

        // boolean equalsIgnoreCase(String str)
        // 判断字符串内容是否相同,不区分大小写
        System.out.println(s.equalsIgnoreCase("Hello World!"));
        System.out.println(s.equalsIgnoreCase("Hello World!")); 
        System.out.println("--------------------");  

        // boolean contains(String str)
        // 判断字符串对象是否包含指定的字符串
        System.out.println(s.contains("llo"));  
        System.out.println(s.contains("orr"));  
        System.out.println("--------------------");  

        // boolean startsWith(String str)
        // 判断字符串对象是否以指定的字符串开始  
        System.out.println(s.startsWith("Hel"));  
        System.out.println(s.startsWith("hello"));  
        System.out.println("--------------------");  

        // boolean endsWith(String str)
        // 判断字符串对象是否以指定的字符串结束  
        System.out.println(s.endsWith("orld!"));  
        System.out.println(s.endsWith("world!"));  
        System.out.println("--------------------");  

        // boolean isEmpty()
        // 判断字符串对象或数据是否为空
        System.out.println(s.isEmpty());  
        String s2 = "";  
        System.out.println(s2.isEmpty());  
        // String s3 = null;  
        // NullPointerException 空指针异常  
        // System.out.println(s3.isEmpty());  
    }  
}  

B:获取方法
(1)获取字符串的长度:public int length()
(2)获取指定字符在此字符串中第一次出现的位置:public int indexOf(int ch)
(3)获取指定字符串在此字符串中第一次出现的位置:public int indexOf(String str)
(4)获取在此字符串中第一次出现指定字符的位置,从指定的位置开始搜索:public int indexOf(int ch,int fromIndex)
(5)获取在此字符串中第一次出现指定字符串的位置,从指定的位置开始搜索:public int indexOf(String str,int fromIndex)
(6)获取在此字符串中最后出现的指定字符串的位置:public int lastIndexOf(String str)
(7)lastIndexOf的其他不同方法与indexOf类似
(8)获取字符串中指定位置的字符:char charAt(int index)
(9)获取从指定位置开始到最后的字符串:String substring(int start)
(10)获取指定范围的字符串:public String substring(int beginIndex, int endIndex)
(11)将字符串按照指定规则进行切割,获得一个切割后的字符串数组:public String[] split(String regex)
(12)去除两端空格:public String trim()

例子:

public class StringDemo {

    public static void main(String[] args) throws UnsupportedEncodingException {

        String s = "Hello World!";

        // int length()
        // 获取字符串的长度
        System.out.println(s.length());
        System.out.println("--------------");

        // char charAt(int index)
        System.out.println(s.charAt(2));  
        System.out.println("--------------");

        // int indexOf(int ch)
        System.out.println(s.indexOf('o'));
        System.out.println("--------------");

        // int indexOf(int ch,int fromIndex)
        System.out.println(s.indexOf('o', 5));
        System.out.println("--------------");

        // int lastIndexOf(int ch)
        System.out.println(s.lastIndexOf('o'));
        System.out.println("--------------");

        // int lastIndexOf(int ch,int fromIndex)
        System.out.println(s.lastIndexOf('o', 5));
        System.out.println("--------------");

        // String substring(int start) 
        System.out.println(s.substring(4));  
        // String substring(int start,int end)
        System.out.println(s.substring(4, 8));  
        System.out.println("--------------");

        // String[] spilt(String regex)
        String strs = "hello|world|hey"
        System.out.println(s.spilt("|"));

    }
}

C:转换功能
(1)把字符串转换成字节数组:public byte[] getBytes()
(2)把字符串转换成字符数组:public char[] toCharArray()
(3)把字符数组转换成字符串:public static String copyValueOf(char[] chs)
(4)把字符数组转换成字符串:public static String valueOf(char[] chs)
(5)把int(基本类型)转换成字符串:public static String valueOf(int i)
(还有其他基本类型的转换)
(6)把字符串变成小写:String toLowerCase()
(7)把字符串变成大写:String toUpperCase()
(8)拼接字符串:String concat(String str)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 创建字符串对象  
        String s = "Hello World!";  

        // byte[] getBytes()
        byte[] bys = s.getBytes();  
        for (int x = 0; x < bys.length; x++) {  
            System.out.println(bys[x]);  
        }  
        System.out.println("-----------------");  

        // char[] toCharArray()  
        char[] chs = s.toCharArray();  
        for (int x = 0; x < chs.length; x++) {  
            System.out.println(chs[x]);  
        }  
        System.out.println("-----------------");  

        // static String copyValueOf(char[] chs)
        char[] chs2 = { '大', '佬', 's', 'n', 'm' };  
        String s2 = String.copyValueOf(chs2);  
        System.out.println(s2);  
        System.out.println("-----------------");  

        // static String valueOf(char[] chs)  
        String s3 = String.valueOf(chs2);  
        System.out.println(s3);  
        System.out.println("-----------------");  

        // static String valueOf(int i)  
        int i = 666;  
        String s4 = String.valueOf(i);  
        System.out.println(s4);  
        System.out.println("-----------------");  

        // String toLowerCase()
        System.out.println(s.toLowerCase());  
        // String toUpperCase() 
        System.out.println(s.toUpperCase());  
        System.out.println("-----------------");  

        // String concat(String str) 
        String s5 = "hello";  
        String s6 = s5 + "world";  
        String s7 = s5.concat("world");  
        System.out.println(s6);  
        System.out.println(s7);  
    }  
}  

D:替换功能
(1)用新的字符去替换指定的旧字符:String replace(char oldChar,char newChar)
(2)用新的字符串去替换指定的旧字符串:String replace(String oldString,String newString)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 创建字符串对象  
        String s1 = "Hello";  
        String s2 = "Hello";
        //char与String的区别在于单引号与双引号
        System.out.println(s1.replace('H', 's'));   
        System.out.println(s2.replace("H", "S"));   

    }  
}  

E:字典顺序比较功能
(1)返回前后比较的两个字符串的ACSII码的差值:public int compareTo(String str)
如果两个字符串首字母不同,则该方法返回首字母的ACSII码的差值
(2)忽略大小写,返回前后比较的两个字符串的ACSII码的差值:public int compareToIgnoreCase(String str)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 创建字符串对象  
        String s1 = "Hello";  
        String s2 = "hello";
        String s3 = "aello";
        String s4 = "Helle";

        System.out.println(s1.compareTo(s2));   //-32
        System.out.println(s1.compareTo(s3));   //-25
        System.out.println(s1.compareTo(s4));   //10
        System.out.println("----------------------");

        System.out.println(s1.compareToIgnoreCase(s2));     //0
        System.out.println(s1.compareToIgnoreCase(s3));     //7
        System.out.println(s1.compareToIgnoreCase(s4));     //10
    }  
}  

二、常见问题
1、字符串比较
这里可以包括了其他类型的比较,此处仅用String。

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

第一个:s1==s2。结果为true,s1和s2引用的“hello”是常量,在常量池中,故是true。
第二个:s1==s3。结果为false,s3是通过new创建的对象,存放在堆内存中,所以比较时不一样。
第三个:s1==s4。结果为false,同理。
第四个:s1.equals(s3)。结果为true。equals是比较两者内容是否相同。
第五个:s1.equals(s4)。结果为true,同理。

2、String的内容是否能够改变?
这个涉及到了final。final修饰后,指的是,引用变量不能变,引用变量所指向的对象中的内容还是可以改变的。
通常看到修改的String内容,只是String修改了内容指向,原本的内容并未改变。

3、String s = new String(“abc”)创建了多少个String对象?
两个或一个,”abc”对应一个对象,这个对象放在字符串常量缓冲区,常量”abc”不管出现多少遍,都是缓冲区中的那一个。new String每写一遍,就创建一个新的对象,它一句那个常量”abc”对象的内容来创建出一个新String对象。如果以前就用过’abc’,这句代表就不会创建”abc”自己了,直接从缓冲区拿。

4、String和StringBuilder和StringBuffer的区别
String、StringBuilder和StringBuffer,它们可以储存和操作字符串,即包含多个字符的字符数据。
这个String类提供了数值不可改变的字符串。而这个StringBuilder和StringBuffer类提供的字符串进行修改。
String覆盖了equals方法和hashCode方法,而StringBuffer没有覆盖equals方法和hashCode方法,所以,将StringBuffer对象存储进Java集合类中时会出现问题。
StringBuilder和StringBuffer的区别是是否安全等等。
当需要频繁修改字符串的时候,建议使用StringBuffer。
单线程操作时推荐使用StringBuilder,效率更高。
多线程时操作推荐使用StringBuffer,更加安全。

5、对乱序的字符串(字符串中的字符是乱序的)进行排序

public class StringDemo {  
    public static void main(String[] args) {  
        String s = "xzcnjeum";
        char[] chs = s.toCharArray();
        //排序方法不限
        for(int i = 0;i<chs.length;i++){
            for (int j = 0; j < chs.length - 1 - i; j++) {  
                if (chs[j] > chs[j + 1]) {  
                    char ch = chs[j];  
                    chs[j] = chs[j + 1];  
                    chs[j + 1] = ch;  
                }  
            }  
        }
        System.out.println(chs);
    }  
}  

当然还有很多没有写好,也是第一次写学习笔记,如果有什么问题欢迎指出。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件上传是Web开发中常见的功能之一,Java中也提供了多种方式来实现文件上传。其中,一种常用的方式是通过Apache的commons-fileupload组件来实现文件上传。 以下是实现文件上传的步骤: 1.在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2.在前端页面中添加文件上传表单: ```html <form method="post" enctype="multipart/form-data" action="upload"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 3.在后台Java代码中处理上传文件: ```java // 创建一个DiskFileItemFactory对象,用于解析上传的文件 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置缓冲区大小,如果上传的文件大于缓冲区大小,则先将文件保存到临时文件中,再进行处理 factory.setSizeThreshold(1024 * 1024); // 创建一个ServletFileUpload对象,用于解析上传的文件 ServletFileUpload upload = new ServletFileUpload(factory); // 设置上传文件的大小限制,这里设置为10MB upload.setFileSizeMax(10 * 1024 * 1024); // 解析上传的文件,得到一个FileItem的List集合 List<FileItem> items = upload.parseRequest(request); // 遍历FileItem的List集合,处理上传的文件 for (FileItem item : items) { // 判断当前FileItem是否为上传的文件 if (!item.isFormField()) { // 获取上传文件的文件名 String fileName = item.getName(); // 创建一个File对象,用于保存上传的文件 File file = new File("D:/uploads/" + fileName); // 将上传的文件保存到指定的目录中 item.write(file); } } ``` 以上代码中,首先创建了一个DiskFileItemFactory对象,用于解析上传的文件。然后设置了缓冲区大小和上传文件的大小限制。接着创建一个ServletFileUpload对象,用于解析上传的文件。最后遍历FileItem的List集合,判断当前FileItem是否为上传的文件,如果是,则获取文件名,创建一个File对象,将上传的文件保存到指定的目录中。 4.文件上传完成后,可以给用户一个提示信息,例如: ```java response.getWriter().write("File uploaded successfully!"); ``` 以上就是使用Apache的commons-fileupload组件实现文件上传的步骤。需要注意的是,文件上传可能会带来安全隐患,因此在处理上传的文件时,需要进行严格的校验和过滤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值