Вставка в строку переменной java

Java String Interpolation with Examples

In this article, we will look at the concept of String Interpolation. We will look at its description, the need for String Interpolation. Also, we look at different techniques to perform String Interpolation with implementation in Java.

String Interpolation is a process where we evaluate a String containing one or more Placeholders (Temporary Name or Substitute) by replacing it with their corresponding values. It allows to dynamically print out text output. So, in short String Interpolation allows us to put variables right inside the String. These variables are then replaced with their actual values at runtime.

Need of String Interpolation

String Interpolation is an easier way to concatenate strings together without excessive syntax. Replacing the variable with their actual values avoids repetitive use of variables while printing the text output. Hence, it makes our code readable, compact, and efficient in writing large variable names or text. Consider this example:

Here, we print the Student Details, we use the ‘+’ operator to concatenate the variables with the Text Strings while printing the details and it makes the code look messy. If we have more than 10 variables the code will become less readable when we concatenate all of them using the ‘+’ operator and print them. So, this is a perfect example where we could use String Interpolation.

Читайте также:  Html event on visible

Ways to Implement String Interpolation in Java

In Java, String Interpolation can be done in the following ways:

  1. Using the format() method of String class.
  2. Using MessageFormat Class.
  3. And, Using StringBuilder or StringBuffer Class.

Let us look at each in detail:

Using String.format() Method

The String class in Java provides a format() method to format String literals or objects. Its use is that it separates the text with the expression and variable name. Let us look at the general syntax for the method which we wi.

public static String format(String text, Object Parameters)

The Parameters to the method will be the variable name which will be replaced with the placeholders. The Placeholders(%s for string) in the input String text must sequentially fit in relative to the values of the variables provided at the end of the expression. The method returns a string so we can use it to format the String first then print it. But, for simplicity, we use it in a simple Print Statement. Now, let us understand this with an example:

System . out . println ( String . format ( «Student Name: %s, School: %s, Address: %s, City: %s, PinCode: %s» ,

Student Name : Sean Henry , School : St . Palestine School , Address : 501 Cannaugh Street , City : California , PinCode : 900012

Explanation: Here, we use the format method to replace the string by using the %s operator which works as a placeholder for a string. We can also perform this for other data types like %d for int, %f for float, etc. For more details on the method refer here.

Using MessageFormatClass

In Java, the MessageFormat Class present in java.text package provides another implementation of the format method. The implementation here is a bit different than we saw above. The difference lies in the arrangement of placeholders. The placeholders in this method are written using the indexes such as ,,.. and so on. Let us look at the syntax of this method:

public static String format(String text, Object Parameters)

For Example: Consider this text: ” is Fun to Learn”, Here denotes the placeholder to replace we can pass any variable in Parameters. Like we can have a variable name=”Java” and we can place it. The text will be now: Java is Fun to Learn.

Note: The Indexing starts from 0. The first variable in arguments will replace it and so on.

This can have some good advantages over the format function in the string class as it can avoid repetition of using the same variable again and again. Also, we can use this method in the same way for integers or other data types.

Let us look at the implementation.

Источник

Как вставить переменную в строку java

Чтобы вставить переменную в строку Java , вы можете использовать оператор + для объединения строк и переменных.

Пример, используя оператор + :

String name = "Alice"; int age = 30; String message = "Привет, меня зовут " + name + " и мне " + age + " лет."; 

Есть также другой подход, который использует метод String.format() :

String name = "Bob"; int age = 25; String message = String.format("Привет, меня зовут %s и мне %d лет.", name, age); 

В этом примере мы использовали метод String.format() для создания строки message . В качестве первого аргумента мы передали шаблон строки с плейсхолдерами %s и %d , которые будут заменены значениями переменных, переданными вторым и последующими аргументами метода.

Источник

Вставить переменные в строку

Я хочу использовать переменную в строке, но не знаю, как это сделать.

private AbstractAction tester = new AbstractAction("test love match") < @Override public void actionPerformed(ActionEvent arg0) < match.setText("text \n text (VARIABLE) text \n text"); // >; 

О каком языке вы говорите? Добавьте его как тег к вашему вопросу. — deceze

Ява, по-моему. Но, пожалуйста, не заставляйте нас гадать. — Damien_The_Unbeliever

4 ответы

Вы можете попробовать использовать String.format , особенно если у вас есть несколько переменных, которые вы хотели бы использовать таким образом в одной строке:

match.setText(String.format("text \n text %s text \n text", variable)); 

match.setText("text \n text " + yourText + " text \n text"); 

Если вы хотите использовать строку из своих ресурсов, вы можете сделать это следующим образом:

String yourText = res.getString(R.string.nameofyourtext); match.setText(yourText); 

Таким образом, вы можете легче редактировать и управлять своими строками в файле strings.xml (res/values/strings.xml).

Проблема с решением заключается в том, что оно не позволяет легко экстернализовать строки;) — m0skit0

На самом деле это не было частью вопроса и на самом деле возможно (получить строку из res и поместить в объект String) — Бенджамин Швальб

Правда, это не часть вопроса, но помогает решить, какой ответ является лучшим. И да, это возможно, но сложнее, чем другие ответы здесь. Кроме того, вы создаете 3 разных объекта String и объединяете их. Все это определенно делает ответ arshajii (например) лучше во всех аспектах. — m0skit0

Правильно, моя ошибка. Затем вы используете 3 строки, и все те же проблемы сохраняются. Например, это строка: «I need to eat %s tomorrow» который в вашем случае был бы «I need to eat » + whatevervariable + » tomorrow» . В вашем случае вам нужно экстернализовать «I need to eat » , whatevervariable и » tomorrow» . Эта экстернализация строки не имеет смысла. Что такое » tomorrow» ? И не говорить о проблемах перевода, когда например » tomorrow» должен быть перед глаголом для некоторых грамматических проблем языка. Я думаю, вы поняли суть 😉 — m0skit0

Да, но извините, вопрос НЕ о том, как связать. «Я хочу использовать переменную в строке, но не знаю, как это сделать» Не «Я не знаю, как объединить». Речь идет о том, как заменить подстроку переменной. И я просто указываю на недостатки в вашем ответе. Опять же, ответ arshajii лучше во всех аспектах для заданного здесь вопроса. — m0skit0

То, что вы ищете, это оператор конкатенации «+».

Если строка name содержит «Dave», этот код Java даст String :

[ В Java мы не говорим о переменные, Мы говорим о объекты. ]

Источник

Оцените статью