[Introduction to Java] Handling of character strings (String class, StringBuilder class)

Purpose

For those who have just started learning programming including the Java language, and those who have already learned it, for review This time I'm writing to learn about ** string manipulation **.

[Introduction to Java Table of Contents] -Variables and typesType conversion -Variable Scope ・ Operation of character strings ← Now here -Array operationOperator ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handlingAbout lambda expressionAbout Stream API

What is the String class?

This class is provided as a data type that can store multiple characters. (Class that handles character strings)

You'll often see a string enclosed in " " and assigned to a variable.

python


String msg = "Hello World!!!";
System.out.println(msg); // Hello World!!!

You can also explicitly assign it to a variable by writing new String. You can also turn a char type array into a String type character string.

python


String banana = new String("banana");
System.out.println(banana); //banana

//You can pass a char type array
String tomato;
char[] chars = {'To', 'Ma', 'To'};
tomato = new String(chars);
System.out.println(tomato); //Tomato

In the String class, if you reassign a different string to an initialized String type variable, the original string will not be rewritten. Since it is an immutable object, it has the characteristic that the reference destination has changed (a new area has been secured).

Compare it with an array of the same reference type (mutable).

python


//Immutable example
String a = "Ah";
String b = a;
a = "I";
System.out.println(a); //I
System.out.println(b); //Ah

//Mutable (variable) example
int[] x = {1, 2, 3};
int[] y = x;
x[0] = 100;

for (int xVal : x) {
  System.out.print(xVal + " "); // 100 2 3
}

for (int yVal : y) {
  System.out.print(yVal + " "); // 100 2 3
}

String class method introduction

There are many methods provided by the String class. The syntax is String type variable name.method name ();.

I will introduce some.

charAt

This method returns the char type at the index specified by the argument. If the argument is negative and is equal to or greater than the length of the string, an exception will be thrown.

python


String name = "Keisuke Honda";
System.out.println(name.charAt(3)); //Ke

//The following raises an exception
System.out.println(name.charAt(7)); //Exception occurs
System.out.println(name.charAt(10)); //Exception occurs

concat

This method concatenates the specified string at the end.

python


String greet = "Good morning";
System.out.println(greet.concat("There is.")); // おはようThere is.

equals

A method that compares a string with the object specified by the argument and returns a boolean.

python


String name = "Keisuke Honda";
System.out.println(name.equals("Little Honda")); // false
System.out.println(name.equals("Keisuke Honda")); // true

indexOf

This method returns the index of the position where the argument character first appears. Returns -1 if the character is not in the string.

python


String str = "banana";
System.out.println(str.indexOf('a')); // 1
System.out.println(str.indexOf('z')); // -1

length

A method that returns the length of a string.

python


String name = "James Harden";
System.out.println(name.length()); // 10

replace

This method replaces the character of the first argument with the character specified by the second argument and returns the resulting string.

python


String name = "Bobobo-bo Bo-bobo";
System.out.println(name.replace("Bo", "Ba")); // BaBaBaーBa・BaーBaBa

isEmpty

This method returns true only when length () is 0.

python


String teruma = "I am here";
System.out.println(teruma.isEmpty()); // false
String none = "";
System.out.println(none.isEmpty()); // true

Since there are too many methods to introduce all of them, the other methods are [Oracle String class](https://docs.oracle.com/javase/jp/11/docs/api/java.base/java/ Please refer to lang / String.html).

What is the StringBuilder class?

This class handles strings in the same way as the String class. It is possible to change the character string stored in the variable. (The original character string can be rewritten) Because the StringBuilder class is ** mutable object **.

To create a StringBuilder type string, use the new keyword as you did when creating the array.

python


StringBuilder sb = new StringBuilder("Hello World!!!");
System.out.println(sb); // Hello World!!!

If you try to assign directly like the String class, an error will occur.

error


StringBuilder name = "Tanaka"; // Type mismatch: cannot convert from String to StringBuilder

StringBuilder class method introduction

There are many methods provided by the StringBuilder class. The syntax is StringBuilder type variable name.method name (); like the String class.

I will introduce some.

append

This method adds the character string specified by the argument to the current character string.

python


StringBuilder name = new StringBuilder("Tanaka");
System.out.println(name); //Tanaka
name.append("Marx");
System.out.println(name); //Tanaka Marcus
name.append("Tulio Tanaka");
System.out.println(name); //Marcus Tulio Tanaka

insert

This method inserts the character string specified by the argument before the character at the position specified by the argument.

python


StringBuilder member = new StringBuilder("Yanagisawa, Volume");
member.insert(3, "Tamada..."); //Because it is 3,"roll"The insertion position is in front of
System.out.println(member); //Yanagisawa, Tamada...roll

delete

This method deletes the characters in the position from the first argument to the position immediately before the position of the second argument.

python


StringBuilder member = new StringBuilder("Cloud, Aeris, Tifa, Barrett");
member.delete(5, 10); //Since the start position is 5, "d", and the end position is 10, ","
System.out.println(member); //Cloud, Tifa, Barrett

replace

This method replaces the character at the position immediately before the position of the first argument to the position of the second argument with the character string specified by the third argument.

python


StringBuilder sb = new StringBuilder("Dufufufu!!");
sb.replace(2, 5, "Lalala"); // 開始位置2なので「フ」から、終了位置5なので「フ」までの文字列を第三引数の文字「Lalala」に置換する
System.out.println(sb); //Durarara!!

substring

It is a method that returns a substring from the position specified by the argument to the end.

python


StringBuilder oosako = new StringBuilder("It ’s not odd");

//Returns the string from the second index to the end
System.out.println(oosako.substring(2)); //It ’s not odd

Since the StringBuilder class also has a large number of methods, we cannot introduce all of them, so the other methods are [Oracle StringBuilder class](https://docs.oracle.com/javase/jp/11/docs/api/java.base/ Please refer to java / lang / StringBuilder.html).

Summary of how to combine strings

It turns out that there are multiple ways to combine strings.

Plus operator


String str1 = "Hello";
String str2 = "World!!!";
String greet = str1 + str2;
System.out.println(greet); // HelloWorld!!!

Concat method of String class


String str = "Hello";
String greet2 = str.concat("World!!!");
System.out.println(greet2); // HelloWorld!!!

Append method of StringBuilder class


StringBuilder sb = new StringBuilder("Hello");
StringBuilder greet3 = sb.append("World!!!");
System.out.println(greet3); // HelloWorld!!!

The output result is the same, but the process up to that point is different.

Precautions for string comparison

Now, let's compare each variable using the == operator. Since the output result is the same, I thought that it would be true,

python


//Plus operator
String str1 = "Hello";
String str2 = "World!!!";
String greet = str1 + str2;
System.out.println(greet); // HelloWorld!!!

//Concat method of String class
String str = "Hello";
String greet2 = str.concat("World!!!");
System.out.println(greet2); // HelloWorld!!!

System.out.println(greet == greet2); // false

The string ** HelloWorld !!!** is the same, but false. When comparing reference types using the `== operator, you will get this result because you are comparing whether the references are the same. ``

The comparison result also changes depending on the method of declaring the character string.

** If you create a string with new String () **, that string will always be generated in the new area. Otherwise, if the same string already exists, it will refer to the existing string. Therefore, when comparing with the == operator, the result is as follows.

python


String str1 = "Yamada";
String str2 = new String("Yamada");
String str3 = "Yamada";

System.out.println(str1 == str2); // false
System.out.println(str1 == str3); // true

If you want to compare strings in the String class, use the ʻequals method` to compare.

python


//Plus operator
String str1 = "Hello";
String str2 = "World!!!";
String greet = str1 + str2;
System.out.println(greet); // HelloWorld!!!

//Concat method of String class
String str = "Hello";
String greet2 = str.concat("World!!!");
System.out.println(greet2); // HelloWorld!!!

//I'm comparing strings in variables, not comparing references
System.out.println(greet.equals(greet2)); // true

By the way, StringBuilder rewrites the existing string, so Comparing the variable sb with the variable greet3 returns true.

python


StringBuilder sb = new StringBuilder("Hello");
StringBuilder greet3 = sb.append("World!!!");
System.out.println(greet3); // HelloWorld!!!

System.out.println(sb == greet3); // true

At the end

I learned about the String class and StringBuilder class for handling strings.

When comparing strings, you have to be careful not to do anything unintended. Also, I want to be able to understand and handle the methods of each class that I could not introduce in this article.

Reference site

** Oracle String Class ** ** Oracle StringBuilder Class ** ** Comparison of strings **

Recommended Posts

[Introduction to Java] Handling of character strings (String class, StringBuilder class)
[Java] Handling of character strings (String class and StringBuilder class)
[Java] Comparison of String type character strings
[java] Summary of how to handle character strings
Various methods of Java String class
I tried to summarize the methods of Java String and StringBuilder
Output of the book "Introduction to Java"
[Java] Introduction to Java
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
[Java] How to use substring to cut out a part of a character string
[Java] How to get to the front of a specific string using the String class
[Java] The confusing part of String and StringBuilder
[Introduction to Java] Basics of java arithmetic (for beginners)
About Java StringBuilder class
About Java String class
Introduction to java command
[Java] How to use compareTo method of Date class
[Java] Convert character strings to uppercase / lowercase (AOJ⑨-swap uppercase and lowercase)
[Java] How to cut out a character string character by character
Introduction to Java for beginners Basic knowledge of Java language ①
[Java] How to erase a specific character from a character string
About full-width ⇔ half-width conversion of character strings in Java
[Java] Practice of exception handling [Exception]
Basics of character operation (java)
Java inflexible String class substring
[Java] Comparison method of character strings and comparison method using regular expressions
How to use java class
[Java] How to convert a character string from String type to byte type
[Java] Comparator of Collection class
[Java] Introduction to lambda expressions
[Java] About String and StringBuilder
Initialization with an empty string to an instance of Java String type
[Java] How to use substring to cut out a character string
Summary of Java Math class
[Java] Introduction to Stream API
[Introduction to rock-paper-scissors games] Java
Display character strings character by character [Note]
[Rails] How to omit the display of the character string of the link_to method
[Rails] How to omit the display of the character string of the link_to method
Cast an array of Strings to a List of Integers in Java
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
How to check for the contents of a java fixed-length string
[Java] Speed comparison of string concatenation
[Introduction to Java] About lambda expressions
[Introduction to Java] About Stream API
Kotlin Class to send to Java developers
Introduction to Functional Programming (Java, Javascript)
[Java] Input to stdin of Process
[Java] Remove whitespace from character strings
StringBuffer and StringBuilder Class in Java
How to decompile java class files
[Java] How to use LinkedHashMap class
Various methods of the String class
[Note] Handling of Java decimal point
Initial introduction to Mac (Java engineer)
Convert iso-2022-jp character string to utf-8
From introduction to usage of byebug
[Algorithm] Descending order of character strings
[Java] Correct comparison of String type
Step-by-step understanding of Java exception handling
[Java] How to use Math class
How to concatenate strings in java