Java string operation

Posted by chrbar on Mon, 22 Nov 2021 19:39:04 +0100

java string operation

String substitution

replace() function to replace a single character. replaceFirst() replaces the first regex match, and replaceAll() replaces all regex matches, The replaceAll and replaceFirst of String use regular expressions!

public class Test{
    public static void main(String args[]){
        String str="Hello World";
        System.out.println( str.replace( 'l','q' ) );
        System.out.println( str.replaceFirst("Hello", "Hi") );
        System.out.println( str.replaceAll("ll", "o") );
        System.out.println( str.replaceAll(".", "o") );
    }
}
}
/* Output results:
Heqqo Worqd
Hi World
Heoo World  
ooooooooooo
*/ 

String slicing

String function substring() function to extract the character of the string between two specified subscripts

public class Test{
    public static void main(String args[]) {
        String str = "this is Java String";
        System.out.println(removeStr(str, 4));
    }
    public static String removeStr(String s, int pos) {
        return s.substring(0, pos) + s.substring(pos + 4);
    }
}
/* Output result: thisJava String   */ 

String lookup

The indexOf() method of String class finds the position where the substring appears in the String, and returns the subscript if it exists

public class Test{
    public static void main(String[] args) {
        String str = "Best wish for lx";
        int intIndex = str.indexOf("lx");
        if(intIndex == - 1){
            System.out.println("String not found");
        }else{
            System.out.println("String position " + intIndex);
        }
    }
}
/* Output result: String position 14 */ 

String segmentation

Use the split(string) method to split the string into an array by specifying a delimiter

    public static void main(String args[]){

        String str = "www-lxacy-com";
        String[] temp = str.split("-");
        for (String x:temp){
            System.out.println(x);
        }

        String str1 = "www.lxacy.com";
        String[] temp1 = str1.split("\\."); // Split string
        for(String x :  temp1){
            System.out.println(x);
        }
    }

You can also use stringtokenizer to set different delimiters to separate strings The default delimiters are: space, tab (\ t), newline (\ n), carriage return (\ r)

import java.util.StringTokenizer;

public class Test{
    public static void main(String args[]){
        String str = "www lxacy ,com";
        StringTokenizer st = new StringTokenizer(str);
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());
        }
        
        StringTokenizer st2 = new StringTokenizer(str, ",");
        while (st2.hasMoreElements()) {
            System.out.println(st2.nextElement());
        }
    }
}
/* Output results:
www lxacy ,com
www lxacy com 
*/ 

String inversion

Use the reverse() function of the StringBuffer class to reverse the string

public class Test{
    public static void main(String[] args){
        String string="bset lx";
        String reverse = new StringBuffer(string).reverse().toString();
        System.out.println("After string inversion:"+reverse);
    }
}
/* Output result: after string inversion: xl tesb */ 

ASCII difference between string comparison initials

String function:

  • compareTo (string)
  • compareToIgnoreCase(String)
  • compareTo(object string)

Compares two strings and returns the difference between the first ASCII letter in the string.

public class Test{
    public static void main(String args[]){
        String str1 = "Hello World";
        String str2 = "hello world";
        Object objStr = str1;

        System.out.println( str1.compareTo(str2) ); //Returns the ASCII difference of the first letter in a string.
        System.out.println( str1.compareToIgnoreCase(str2) ); //ignore case
        System.out.println( str1.compareTo(objStr.toString()));
    }
}
/* Output result: - 32 0 0    */ 

Finds the last occurrence of a string

The string function lastIndexOf(string) finds the last occurrence of the substring string

public class Test{
    public static void main(String[] args) {
        String str = "Hello world ,Hello Lx";
        int lastIndex = str.lastIndexOf("Lx");
        if(lastIndex == - 1){
            System.out.println("Can't find");
        }else{
            System.out.println("Lx Last occurrence of string: "+ lastIndex);
        }
    }
}
/* Output result: 19   */ 

String lowercase to uppercase

The String. toUpperCase() method is used to convert the string from small to uppercase

public class Test{
    public static void main(String[] args) {
        String str = "string";
        String strUpper = str.toUpperCase();
        System.out.println("Convert to uppercase: " + strUpper);
    }
}
/* Output result: convert to uppercase: STRING  */ 

Determine whether two string regions are equal

Use the regionMatches() method to determine whether two string regions are equal.

  • The first parameter, ignoreCase=True, means that the case difference is ignored
  • The second parameter, toffset, means to compare str1 string with str2 from the second character
  • The third parameter, String, is the String str2 to compare
  • The fourth parameter, ooffset, indicates that the comparison starts from the second character of str2
  • The fifth parameter, len, indicates the number of matching digits
public class Test{
    public static void main(String[] args){
        String str1 = "Welcome to BeiJing";
        String str2 = "welcome to beijing";
        boolean match1 = str1.regionMatches(true, 2, str2, 2, 3);
        System.out.println("Return value:" + match1);
    }
}
/* Output result: return value: true  */ 

String formatting

Format the string through the format() method

import java.util.*;
public class Test{
    public static void main(String[] args){
        double e = Math.PI;
        System.out.format("%f%n", e);
        System.out.format(Locale.CHINA  , "%-10.4f%n%n", e);
    }
}
/* Output results:
3.141593
3.1416  
*/