- Как объединить символы в Java?
- 11 ответов
- How to Add char to String in Java
- How to Add Char to String in Java?
- Method 1: Add char to String Using Concatenation Operator “+”
- Method 2: Add char to String Using substring() Method
- Method 3: Add char to String Using append() Method
- Method 4: Add char to String Using insert() Method
- Conclusion
- About the author
- Farah Batool
Как объединить символы в Java?
Как вы объединяете символы в java? Конкатенация строк потребует только + между строками, но конкатенация символов с использованием + изменит значение char на ascii и, следовательно, даст числовой вывод. Я хочу сделать System.out.println(char1+char2+char3. и создать такое строковое слово. Я мог бы сделать
System.out.print(char1); System.out.print(char2); System.out.print(char3);
Но это приведет меня только к символам в 1 строке. Мне нужно это как строка. Любая помощь будет оценена. Спасибо
Смотрите другой Вопрос, чтобы узнать, ПОЧЕМУ использование оператора «+» не удалось ( любимый ответ оттуда).
11 ответов
Вы хотите сделать из них строку?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
String b = "b"; String s = "a" + b + "c";
Собственно компилируется в
String s = new StringBuilder("a").append(b).append("c").toString();
Изменить: как указано в ярлыке, вы также можете сделать это:
Это компилируется следующим образом:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Изменить (2). Исправлено сравнение строк, поскольку, как указывает cletus, компилятор обрабатывает ряд строк.
Цель вышеизложенного — проиллюстрировать, что делает компилятор, а не сообщать вам, что вы должны делать.
Вы не правы. «a» + «b» + «c» становится «abc» во время компиляции. Он оценивается только во время выполнения, если хотя бы один из этих операндов не может быть определен во время компиляции.
@cletus Я только что проверил, и вы правы насчет «a» + «b» + «c». То же самое происходит с буквенными символами, но не при использовании ссылок на переменные. Спасибо, что просветили меня. 🙂
Я не собирался отвечать на этот вопрос, но здесь есть два ответа (которые проголосовали!), которые просто ошибаются. Рассмотрим эти выражения:
String a = "a" + "b" + "c"; String b = System.getProperty("blah") + "b";
Первое оценивается в время компиляции. Второе оценивается в время выполнения.
Так никогда заменить константные конкатенации (любого типа) на StringBuilder, StringBuffer и т.п. Используйте только те, где переменные перехватываются, и обычно только при добавлении большого количества операндов или добавлении в цикл.
Если символы постоянны, это нормально:
Если это не так, рассмотрим следующее:
String concat(char. chars) < if (chars.length == 0) < return ""; >StringBuilder s = new StringBuilder(chars.length); for (char c : chars) < s.append(c); >return s.toString(); >
в качестве подходящего решения.
Однако некоторые могут попытаться оптимизировать:
String s = "Name: '" + name + "'"; // String name;
String s = new StringBuilder().append("Name: ").append(name).append("'").toString();
Хотя это благие намерения, нижняя строка НЕ НЕ.
Почему? Как еще один ответ правильно указал: компилятор делает это за вас. Поэтому, делая это самостоятельно, вы не позволяете компилятору оптимизировать код или не зависеть, если его хорошая идея, код сложнее читать и его излишне сложно.
Для низкоуровневой оптимизации компилятор лучше оптимизирует код, чем вы.
Пусть компилятор выполнит свою работу. В этом случае наихудший сценарий заключается в том, что компилятор неявно изменяет ваш код именно на то, что вы написали. Конкатенирование 2-3 Строки могут быть более эффективными, чем создание StringBuilder, поэтому лучше оставить его как есть. Компилятор знает, что лучше всего в этом отношении.
действительно ты прав. было бы плохим дизайном и глупым, если бы «a» + «b» создал строителя строк. и я также согласен с тем, что только для 1-5 конкатов делать это с +, вероятно, лучше, чем затрачивать усилия на создание StringBuilder.
Компилятор сделает это за вас, но да, в вашем последнем примере это то, что компилятор выводит. Я полностью согласен, что вы не должны делать это самостоятельно, но я думаю, что важно понимать, что происходит.
How to Add char to String in Java
“char” is a primitive data type belonging to the Java wrapper class “Character” that stores 16-bit Unicode characters. Java uses the char data type to store one character that is enclosed in single quotes (‘ ‘), While a “String” is used to hold a group of characters that are arranged in a particular order surrounded by double quotes (” “). Java provides multiple options for adding a new character to a String.
This blog will discuss the procedure of adding char to a String in Java.
How to Add Char to String in Java?
For adding a character “char” to a String, you can use:
- Concatenation Operator “+”
- substring() method
- append() method
- insert() method
Let’s have a look at these methods one by one!
Method 1: Add char to String Using Concatenation Operator “+”
The easiest and most commonly used method to add char to a String is the Concatenation operator “+”. It concatenates the character to a String. You can add additional characters either at the start, middle, or at the end of the String with the help of the “+” operator.
Syntax
The following syntax can be utilized to add char “ch” to a String “str”:
Example 1: Add char at the Start of the String
In this example, we will add the character “H” at the start of a String. To do so, we will create a char named “ch” with the specified values:
Next, we will concatenate the created char with the substring “ello” and store the resultant value in the “s” String:
Finally, we will print the value of our String:
The output shows that the character “H” is now concatenated with the “ello” substring, and the resultant String is “Hello”:
Example 2: Add char at the Middle of the String
Here, we will add a character “n” in the middle of the String:
Now, we will add the value of the created characters in between the “Li” and “ux” substrings, with the help of the “+” operator:
Then, simply print the value of “s” using the “System.out.println()” method:
As you can see, we have successfully added the specified char in the middle:
Example 3: Add char at the End of the String
Now, we will check how to add a character at the end of the String. We will have a character type variable “ch” that stores a character “t”:
Here, we have a String “Linux Hin”, which will be concatenated with the “ch” character and store the resultant value in “s” String:
At last, print the value of String type variable “s” on the console:
Let’s check other methods for adding char to the String in Java.
Method 2: Add char to String Using substring() Method
In Java, another method for adding a character to a String is the “substring()” method. It belongs to the String class.
Syntax
Here is the syntax of the “substring()” method for the specified purpose:
Call the substring() method with a String “s” and split it by passing the start index as a “firstIndex” and the index where you want to add the character as “secondIndex”. Now, add the character using the “+” operator and then concatenate the other part of the String starting from the passed “secondIndex”.
Example
We will add character “n” at the middle of the String using the “substring()” method:
The String “LiuxHint” is stored in the String type variable “s”. We want to add the character “n” before the character “u” that is placed at the “2” index:
We will split the String from the start to the 2nd index of the String “s” using “s.substring(0,2)” and add the character “ch” at that place, and then concatenate the remaining part of the String with “s.substring(2)” the start index of that and save it in a String type variable “sb”:
Finally, print the value of “sb” on the console window:
The output signifies that the “n” character is added to the “LiuxHint” String, and it becomes “LinuxHint”:
There are some other methods for adding characters to a String. Let’s move towards them.
Method 3: Add char to String Using append() Method
The “append()” method of the “StringBuilder” class is also used to add a character to a String in Java. In the StringBuilder class, you can build a String with concatenation. It works the same as the “+” operator.
Syntax
Follow the below syntax for using the “append()” method:
The append() method will be called with the object of the StringBuilder class “sb”, and it takes a character “ch” as an argument.
In this example, we will add the character “t” at the end of the String “LinuxHin” by utilizing the “append()” method:
The String “LinuxHin” will store in a String type variable “s”:
We will create an object “sb” of the “StringBuilder” class:
Now, we will call the “append()” method with object “sb” by passing it in a String “s” and then again call “append()” method and pass character “ch” as an argument:
Finally, we will print the object “sb” that contains the resultant String by adding a character in it:
The output shows that we have successfully added the character “t” at the end of the “LinuxHin” substring:
There is one more method for adding characters in between the Strings. Let’s check it out.
Method 4: Add char to String Using insert() Method
The “insert()” method of the “StringBuffer” class is also used to add characters in a String in Java. It adds the character at the specified position, similar to the substring() method. The characters and substrings can also be placed in the middle or appended at the end of a StringBuffer.
Syntax
The “insert()” method has the following syntax:
The insert() method is called with the object of the StringBuffer class “sb” by passing an “index” where you want to add the “ch” character.
Example
In this example, we will add the character “u” at the 3rd index of the String “LinxHint”. For this purpose, we have created a “ch” character:
The String “LinxHint” is stored in the “s” variable:
Then, we will create an object “sb” of the StringBuffer class and pass the created String as an argument to it:
Call the “insert()” method and pass character “ch” and the index as “3”:
Lastly, we will print the value of object “sb” with the help of the “System.out.println()” method:
The output shows that the character “u” is successfully added in the String “LinuxHint” at the 3rd index:
We have compiled all the methods related to adding a character to a String in Java.
Conclusion
For adding characters to a String, you can use the Concatenation Operator “+”, substring(), append(), and insert() method. The most common and easiest way to add character to a String. You can also add character at any place at either the String’s start, end, or middle by utilizing the “+” operator and the append() method. While for other methods, you have to mention the index. In this blog, we have discussed the methods for adding a character to a String in Java with detailed examples.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.