目录

1、字符串的trim()方法

2、字符串的substring(int a,int b)

3、字符串的charAt()

4、字符串中插入字符StringBuilder

4.1、StringBuilder中的append()

4.2、StringBuilder中的insert(int index,char c)

4.3、StringBuilder中的reverse()

5、数字转换为字符串

6、字符串的indexOf()

另外补充一种情况:反转List集合里面的元素就使用以下方法:Collections.reverse(list)


1、字符串的trim()方法

trim()方法:删除字符串首尾的空格

String s1 = "  abcdef";   //abcdef
        String s2 = "abcdef  ";  //abcdef
        String s3 = "abcdef";    //abcdef
        String s4 = "  abcdef  ";//abcdef

2、字符串的substring(int a,int b)

substring(int a,int b)方法表示截取从字符串a下标到b-1下标  (int a,int b)为左闭右开

String str="abcdef";
        String s =  str.substring(1,4);//截取下标为1,2,3的字符串
        System.out.println(s);//打印bcd

3、字符串的charAt()

获取字符串的单个字符,charAt(int a)  a为字符串中的下标值


4、字符串中插入字符StringBuilder

不保证是同步的,在使用优先级上,优先于使用StringBuffer,因为StringBuilder在大多数中实现的更快

4.1、StringBuilder中的append()

append()表示在字符串的末尾拼接其他字符串

StringBuilder str = new StringBuilder("abc");
        System.out.println(str);//打印abc
          str.append("def");
        System.out.println(str);//打印abcdef

4.2、StringBuilder中的insert(int index,char c)

StringBuilder中的 insert() 表示在字符串下标index位置插入char参数的字符串表示形式,该下标位置元素(包括该位置元素)及后面下标的字符串都往后移动

StringBuilder str = new StringBuilder("abc");
        String s = "111";
        str.insert(1,s);//在下标1位置插入字符串s
        System.out.println(str);//打印a111bc

4.3、StringBuilder中的reverse()

reverse()为字符串反转的方法,在StringBuilder下使用

StringBuilder str = new StringBuilder("abcdef");
        System.out.println(str.reverse());//打印fedcba

5、数字转换为字符串

public class IntToString {
    public static void main(String[] args) {
        Integer num = 456;

        //方式1
        String str1 = String.valueOf(num);
        System.out.println("方式1的结果:" + new StringBuilder(str1).reverse().toString());

        //方式2
        String str2 = Integer.toString(num);
        System.out.println("方式1的结果:" + str2);

        //方式3 (推荐使用,最简单)
        String str3 = num + "";
        System.out.println("方式1的结果:" + str3);
    }
}

6、字符串的indexOf()

        字符串的indexOf() 可以快速判断字符串B是否存在字符串A中,若存在则返回字符串B在字符串A中的首字符下标 

String A="abcdef";
String B="bc"; 
int i = A.indexOf(B);//返回字符串B在字符串A第一个字符下标,若不存在则返回-1
System.out.println(i);//输出1

另外补充一种情况:反转List集合里面的元素就使用以下方法:Collections.reverse(list)

//此处代码为伪代码  
   String s = "qqwd";
 List list = new ArrayList();
       list.add(s)
    Collections.reverse(list);//调用Collections中的reverse方法来反转List
    for(int i=0;i<list.size();i++){
           System.out.print(list.get(i));
    }