[java] Summary of how to handle character strings

Summarize how to handle strings in java.

First, the character string type is described, the basic operations of the String type are summarized, and finally, the character string operations using StringBuilder are summarized.

String type

Characteristics of String type

The String type is immutable. That is, when a character string is concatenated or cut out by an operation, the character string itself does not change, but a new character string is created in the storage area. This has the following features.

--The maintainability of the program is improved because no destructive changes occur. --Easy to see the program --Inefficient memory --Limited string operations that can be done with methods

StringBuffer and StringBuilder

The mutable (variable) StringBuilder class and StringBuffer class solve this inefficiency and difficulty in operation.

StringBuilder and StringBuffer are used in the same way, the only difference is that StringBuffer is thread-safe and StringBuilder is not thread-safe. Thread-safe is a term that means that problems do not occur when multiple threads process a code in parallel.

Therefore, when multi-thread processing is not performed, it is better to use StringBuilder, which is faster than synchronous processing. How to use it will be described later.

Basic operation of String type

Perform basic operations on the following String type character string S.

String str = "a,b,c";

Get length

Get the length of the string. The return value is int type.

str.length()

Get the Nth character

The return value is char type.

str.charAt(int index)

Combine strings

You can combine strings with +.

str += "String type string"

Split the string

Splits the string with the specified delimiter. If the delimiter is "", it will be split character by character. The return value is a String type array.

str.split("Delimiter")

Cut out a character string

endIndex can be omitted. Note that if specified, endIndex is not included. The return value is a String type.

str.substring(int beginIndex, int endIndex)

String comparison

Since the reference value of String type may be different even if it is the same character string, it cannot be compared with == like python. The return value is boolean.

str.equals("String type string")

With IgnoreCase, you can compare by ignoring uppercase and lowercase letters.

str.equalsIgnoreCase("String type string")

Dictionary order comparison

Returns a number that indicates how far before the string to be compared is str. That is, it returns a negative value if the string to be compared is after str, a positive value if it is before, and 0 if it matches. The return value is int type.

str.compareTo("String type string")
"a".compareTo("b") //-1
"b".compareTo("a") //1
"a".compareTo("a") //0

Also here, if you add IgnoreCase, you can compare by ignoring uppercase and lowercase letters.

str.compareToIgnoreCase("String type string")

Search

Authenticity judgment

Does it contain the specified string? The return value is boolean.

str.contains("String type string")

If you want to use regular expressions, use the matches method.

str.matches("Regular expressions")

Prefix match. The return value is boolean.

str.startsWith("String type string")

Backward match. The return value is boolean.

str.endsWith("String type string")
Get index

Returns the index of the position where the specified substring first appears. When an argument is added, the index of the position where it first appears after that is returned. The return value is int type.

str.indexOf("String type string")
str.indexOf("String type string", int fromIndex)

Similarly, there is also a method called LastindexOf that returns the index of the last occurrence position.

str.lastIndexOf("String type string")
str.lastIndexOf("String type string", int fromIndex)

String replacement

If the specified string is included, replace all of them. The return value is a String type.

str.replace("Specified character string", "Replacement string")

You can also use regular expressions with replaceAll.

str.replaceAll("Specified character string (regular expression possible)", "Replacement string")

If you want to replace only the first specified character string, use replaceFirst. Like replaceAll, replaceFirst can use regular expressions.

str.replaceFirst("Specified character string (regular expression possible)", "Replacement string")

Uppercase / lowercase conversion

The return value is a String type.

str.toUpperCase() //Uppercase
str.toLowerCase() //To lowercase

Conversion to string

Various types including numbers can be converted to strings with String.valueOf (). The return value is a String type.

String.valueOf(int num)

If a char type array is used as an argument, it will be a character string that connects the arrays.

char[] c = {'a', 'b', 'c'};
String.valueOf(c) //"abc"Is returned

This is convenient when you want to get the number of digits in a number.

int N = 100000;
String.valueOf(N).length() //It turns out to be 6 digits

Summary of how to use StringBuilder

Conversion from String to StringBuilder

Build as follows.

StringBuilder sb = new StringBuilder(str)

Conversion from StringBuilder to String

Can be converted to String type with toString.

sb.toString()

String concatenation

append corresponds to + of String type. The argument may be int type or char type instead of String type.

sb.append("What you want to combine")

If you want to insert it anywhere, use insert.

sb.insert(int index, "What you want to combine")

Delete substring

You can specify the index and delete the substring. Like other methods, it does not include endIndex.

sb.delete(int beginIndex, int endIndex)

Change the character of any index

You can replace any index character with another with setCharAt.

sb.setCharAt(int index, char c)
//sb.setCharAt(1, 'z')If so, it becomes azc

Inversion of string

Reversed character string is obtained by reverse.

sb.reverse()

String replacement

Converts a substring with index specified to an arbitrary string.

sb.replace(int start, int end, "Replacement string")

Same operation as String type

Get length
sb.length()
Get the Nth character
sb.charAt(int index)
Get index
sb.indexOf("String type string")
sb.indexOf("String type string", int fromIndex)
sb.lastIndexOf("String type string")
sb.lastIndexOf("String type string", int fromIndex)

Summary

The operations of String type and StringBuilder class are summarized. Normally, you can use the String type, but if you perform operations many times and it takes a long time to execute, or if you want to perform operations such as inversion, you should use the StringBuilder class.

Also, in competitive programming, it takes time to output a character string many times, so in that case it is better to append to StringBuilder and output it all at once at the end. If you need a line break, append "\ n".

reference

Oracle Help Center Description of String class Description of StringBuilder class

Recommended Posts

[java] Summary of how to handle character strings
[java] Summary of how to handle char
[Java] [Maven3] Summary of how to use Maven3
[Java] Summary of how to abbreviate lambda expressions
Summary of Java communication API (1) How to use Socket
Summary of Java communication API (3) How to use SocketChannel
Summary of Java communication API (2) How to use HttpUrlConnection
Summary of how to implement default arguments in Java
How to concatenate strings in java
Differences in how to handle strings between Java and Perl
[Introduction to Java] Handling of character strings (String class, StringBuilder class)
How to make a Java calendar Summary
Summary of how to write annotation arguments
[Java] Comparison of String type character strings
Summary of how to select elements in Selenium
Summary of how to create JSF self-made tags
[Java] How to use substring to cut out a part of a character string
[Java] How to get the authority of the folder
Summary of Java support 2018
How to concatenate strings
[Java] How to easily get the longest character string of ArrayList using stream
[Java] How to get the URL of the transition source
[Java] How to use compareTo method of Date class
How to write Scala from the perspective of Java
[Java] Types of comments and how to write them
[Java Silver] Summary of points related to lambda expressions
[Java] Convert character strings to uppercase / lowercase (AOJ⑨-swap uppercase and lowercase)
[Java] How to get the maximum value of HashMap
Summary of knowledge required to pass Java SE8 Silver
As of April 2018 How to get Java 8 on Mac
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
About full-width ⇔ half-width conversion of character strings in Java
How to execute WebCamCapture sample of NyARToolkit for Java
[Java] Handling of character strings (String class and StringBuilder class)
[Java] How to use Map
How to lower java version
[Java] How to use Map
How to uninstall Java 8 (Mac)
Java --How to make JTable
How to handle uploaded images
[Java11] Stream Summary -Advantages of Stream-
Basics of character operation (java)
How to use java Optional
How to minimize Java images
How to write java comments
[Java] Summary of regular expressions
How to use java class
[Java] Summary of operators (operator)
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] How to use string.format
How to use Java Map
How to set Java constants
Summary of Java language basics
[Java] Summary of for statements
Summary of Java Math class
How to use Java variables
How to handle an instance
How to convert Java radix