String operation method summary


The basic operations of the String class can be divided into the following categories:

Before sorting out these contents, we need to be reminded that we don’t need to manually import the package like other operations for the operation method of the string. The classes such as String and StringBuffer are encapsulated in the java.lang package, and we call the string method That's it!

1. String basic operation method

1) Get the string lengthlength()

格式:int length = str.length();

2) Get the ith character in the stringcharAt(i)

// i is the index number of the string, you can get the character at any position in the string, and save it in the character variable

Format: char ch = str.char(i);

3) Get the character at the specified positiongetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

//First create a char array with a large enough capacity, the array name is array

Format: char array[] = new char[80];

str.getChars(indexBegin, indexEnd, array, arrayBegin);

indexBegin The starting index of the string to be copied
indexEnd The end index of the string to be copied, indexEnd - 1
array The array name of the previously defined char array
arrayBegin The index number of the position where the array array starts to be stored

In this way, we can copy all the characters in the desired range in the string to the character array, and print out the character array.

There is a getBytes() method similar to getChars(), which are basically the same in use, except that the getBytes() method creates an array of byte type, and the byte encoding is the default character set encoding, which is the character represented by the encoding.

Go directly to the code to briefly demonstrate the usage of the three methods:

//String类基本操作方法
public class StringBasicOpeMethod {
    
    
    public static void main(String args[]){
    
    
    
        String str = "如何才能变得像棋哥一样优秀?算了吧,憋吹牛逼!"; //定义一个字符串
        
        System.out.println(str);  //输出字符串
        
        /***1、length()方法***/
        
        int length = str.length();//得到字符串长度
        
        System.out.println("字符串的长度为:"+length);
        
        /***2、charAt()方法***/
        
        char ch = str.charAt(7);  //得到索引为7的字符
        
        System.out.println("字符串中的第8个字符为:"+ch);
        
        /***3、getChars()方法***/
        
        char chardst[] = new char[80]; //定义容量为80的字符数组,用于存储从字符串中提取出的一串字符
        
        str.getChars(0,14,chardst,0);
        
        //System.out.println("字符数组中存放的内容为:"+chardst);//错误,输出的是编码
        
        System.out.println(chardst); //**括号中不可带其他字符串
    }
}

The result of the operation is as followsinsert image description here

Second, the comparison of String strings

Clear numerical values ​​can be compared easily, so how should strings be compared? The comparison of strings is to compare two strings character by character from left to right. The comparison is based on the Unicode encoding value of the current character, and the size of two different characters can be compared.

String comparison is also divided into two categories: one is the comparison of string size, such comparison has three results, greater than, equal to, and less than; another type of comparison is to compare whether two strings are equal, and the resulting comparison There are only two types of results, true and false.

public class StringCompareMethod {
    
    
    public static void main(String args[]){
    
    
        String str1 = "elapant";
        String str2 = "ELEPANT";  //定义两个字符串
        String str3 = "Apple";
        String str4 = "apple";
        
        /***1、compareTo方法***/
        //不忽略字符串字符大小写
        if(str1.compareTo(str2)>0){
    
    
            System.out.println(str1+">"+str2);
        }else if(str1.compareTo(str2) == 0){
    
    
            System.out.println(str1+"="+str2);
        }else{
    
    
            System.out.println(str1+"="+str2);
        }
        
        
        /***2、compareToIgnoreCase()方法***/
        //忽略字符串字符大小写
        if(str1.compareToIgnoreCase(str2)>0){
    
    
            System.out.println(str1+">"+str2);
        }else if(str1.compareToIgnoreCase(str2) == 0){
    
    
            System.out.println(str1+"="+str2);
        }else{
    
    
            System.out.println(str1+"<"+str2);
        }
        
        
        /** 3、equals()方法
        * 	相等情况下必须保证二者长度相等
        */
        //不忽略字符串字符大小写
        if(str3.equals(str4)){
    
    
            System.out.println(str3+"="+str4);
        }else{
    
    
            System.out.println(str3+"!="+str4);
        }


        /***4、equalsIgnoreCase()方法***/
        //忽略字符串字符大小写
        if(str3.equalsIgnoreCase(str4)){
    
    
            System.out.println(str3+"="+str4);
        }else{
    
    
            System.out.println(str3+"!="+str4);
        }
    }
}

The result of the operation is as follows:
insert image description here

3. Conversion between String and other data types

Sometimes we need to do a conversion between strings and other data types, such as converting string data into integer data, or conversely converting integer data into string type data, "20" is a string, and 20 is integer number. We all know that integer and floating-point types can be converted between the two by means of mandatory type conversion and automatic type conversion. Then "20" and 20, two types of data that belong to different types, need to use the String class The data type conversion method provided.

Due to the large number of data types, there are many methods for conversion. Here I will list them in a table:

type of data string to other Other methods of converting to strings 1 Other methods of converting to strings 2
byte Byte.parseByte(str) String.valueOf([byte] bt) Byte.toString([byte] bt)
int Integer.parseInt(str) String.valueOf([int] i) Int.toString([int] i)
long Long.parseLong(str) String.valueOf([long] l) Long.toString([long] l)
float Float.parseFloat(str) String.valueOf([float] f)) Float.toString(str)
double double.parseDouble(str) String.valueOf([double] d) Double.toString([double] b)
char str.charAt() String.valueOf([char] c) Character.toString([char] c)
boolean Boolean.getBoolean(str) String.valueOf([boolean] b) Boolean.toString([boolean] b)

A small demo for a simple test is as follows:

public class StringConvert {
    
    
  public static void main(String args[]){
    
    
  
    /***将字符串类型转换为其他数据类型***/
    boolean bool = Boolean.getBoolean("false"); //字符串类型转换为布尔类型
    int integer = Integer.parseInt("20"); //字符串类型转换为整形
    long LongInt = Long.parseLong("1024"); //字符串类型转换为长整形
    float f = Float.parseFloat("1.521"); //字符串类型转换为单精度浮点型
    double d = Double.parseDouble("1.52123");//字符串类型转换为双精度浮点型
    byte bt = Byte.parseByte("200"); //字符串类型转换为byte型
    char ch = "棋哥".charAt(0);
    
    /***将其他数据类型转换为字符串类型方法1***/
    String strb1 = String.valueOf(bool); //将布尔类型转换为字符串类型
    String stri1 = String.valueOf(integer); //将整形转换为字符串类型
    String strl1 = String.valueOf(LongInt); //将长整型转换为字符串类型
    String strf1 = String.valueOf(f); //将单精度浮点型转换为字符串类型
    String strd1 = String.valueOf(d); //将double类型转换为字符串类型
    String strbt1 = String.valueOf(bt); //将byte转换为字符串类型
    String strch1 = String.valueOf(ch); //将字符型转换为字符串类型
  }
}

Four, String string search

Sometimes we need to find a part of the string or a certain character we need in a very long string. The String class just provides the corresponding search methods. These methods return the index of the target search object in the string. value, so they are all integer values. The specific classification is as follows:

String search is nothing more than two categories: search for a string and search for a single character, and search can be divided into the position where the object appears for the first time and the last time it appears in the string. With one more step, we can narrow down the search Range, finds its first or last occurrence within the specified range.

//字符与字符串查找
public class StringSearchChar {
    
    
  public static void main(String args[]){
    
    
  
    String str = "How qi bocome handsome like qi ge"; //定义一个长字符串
    System.out.println("该字符串为:"+str);
    
    
    /***1、indexOf()方法查找字符首个出现位置格式1,2***/
    
    int index1 = str.indexOf(" "); //找到第一个空格所在的索引
    int index2 = str.indexOf(" ",4); //找到索引4以后的第一个空格所在索引
    
    System.out.println("第一个空格所在索引为:"+index1);
    System.out.println("索引4以后的第一个空格所在索引为:"+index2);
    System.out.println("*****************");
    
    
    /***2、lastIndexOf()方法查找字符最后出现位置格式1,2***/
    
    int index3 = str.lastIndexOf(" "); //找到最后一个空格所在的索引
    int index4 = str.lastIndexOf(" ",10);//找到索引10以后的第一个空格所在索引
    
    System.out.println("最后一个空格所在索引为:"+index3);
    System.out.println("索引10以前最后一个空格所在索引为:"+index4);
    System.out.println("*****************");
    
    
    /***3、indexOf()方法查找子字符串第一次出现位置格式1,2***/
    
    int index5 = str.indexOf("qi"); //找到"qi"子字符串第一次出现位置的索引
    int index6 = str.indexOf("qi",5);//找到索引5以后子字符串"qi"第一个出现位置所在索引
    
    System.out.println("子字符串qi第一次出现位置的索引号为:"+index5);
    System.out.println("索引5以后子字符串qi第一次出现位置的索引号为:"+index6);
    System.out.println("*****************");
    
    
    /***4、lastIndexOf()方法查找子字符串最后一次出现位置格式1,2***/
    
    int index7 = str.lastIndexOf("qi");
    int index8 = str.lastIndexOf("qi",5);
    
    System.out.println("子字符串qi最后一次出现位置的索引号为:"+index7);
    System.out.println("索引号5以后子字符串qi最后一次出现位置的索引号为:"+index8);
  }
}

The result is as follows:
insert image description here

Five, String interception and splitting

This kind of method is to intercept a substring in a long string or split the string into a string array according to the requirements of the regular expression. The specific method is as follows:

//字符串截取与拆分
public class StringCutAndSplit {
    
    
  public static void main(String args[]){
    
    
  
    String str = "How to cut and split strings"; //定义字符串
    System.out.println("字符串为:"+str);
    
    int length = str.length(); //获取字符串长度,保存到变量中
    System.out.println("字符串长度为:"+length);
    
    
    /***1、substring()方法截取出第一个单词和最后一个单词***/
    
    //首先配合indexOf()和lastIndexOf()方法找到第一个单词和最后一个单词前后空格的索引号
    //第一个单词的左范围索引为0,最后一个单词的右范围索引为length-1
    
    int firstIndex = str.indexOf(' '); //找到第一个空格所在位置
    
    int lastIndex = str.lastIndexOf(' '); //找到最后一个空格所在位置
    
    System.out.println("第一个空格的索引号为:"+firstIndex);
    System.out.println("最后一个空格的索引号为:"+lastIndex);
    
    
    //利用substring()方法根据第一个和最后一个单词的索引范围截取出第一个和最后一个单词
    
    String firstWord = str.substring(0,firstIndex); //截取出第一个单词
    
    String lastWord = str.substring(lastIndex+1,length);//截取出最后一个单词
    
    System.out.println("第一个单词为:"+firstWord);
    System.out.println("最后一个单词为:"+lastWord);
    
    
    /***2、split()方法拆分出所有单词***/
    
    String stringArray[] = str.split(" "); //根据空格要求拆分出所有单词保存到字符串数组中
    
    System.out.println("拆分之后的各个词汇为:");
    
    for(int i = 0;i<stringArray.length;i++){
    
    
      System.out.print(stringArray[i]+"\t");
    }
  }
}

The code execution results are as follows:
insert image description here

6. String replacement or modification

Finally arrived at the last category of methods, happy! ! Sometimes we need to replace or modify some substrings in the original string. At this time, we also need some simple, fast and easy-to-use methods provided by the String class.

//字符串替换与修改
public class StringFindandReplace {
    
    
  public static void main(String args[]){
    
    
  
    String str1 = "vbasic";
    String str2 = "Vbasic";
    
    System.out.println("str1 = "+str1);
    System.out.println("str2 = "+str2);
    
    /***1、concat()方法将两字符串合并***/
    
    String str3 = str1.concat(str2);
    
    System.out.println("str1和str2合并后的字符串为:"+str3);
    
    
    /***2、toLowerCase()方法将str1字符全部转换为小写***/
    
    String str4 = str1.toLowerCase();
    
    System.out.println("str1的字符全部转换为小写:"+str4);
    
    
    /***3、toUpperCase()方法将str2字符全部转换为大写***/
    
    String str5 = str2.toUpperCase();
    
    System.out.println("str2的字符全部转换为大写:"+str5);
    
    
    /***4、实现字符串的替换,原字符串内容不变***/
    
    String str6 = str1.replaceFirst("(?i)VBASIC","C++");
    String str7 = str2.replaceFirst("(?-i)VBASIC","C++");
    
    System.out.println("替换后的str1:"+str6);
    System.out.println("替换后的str2:"+str7);
  }
}

The code execution results are as follows:
insert image description here


The law of good things: Everything will be a good thing in the end, if it is not a good thing, it means that it is not the end yet.

Guess you like

Origin blog.csdn.net/Cike___/article/details/128872524