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 types ・ Type conversion -Variable Scope ・ Operation of character strings ← Now here -Array operation ・ Operator ・ 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 handling ・ About lambda expression ・ About Stream API
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
}
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).
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
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).
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.
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
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.
** Oracle String Class ** ** Oracle StringBuilder Class ** ** Comparison of strings **
Recommended Posts