How to including variables within strings? [duplicate] - java

This question already has answers here:
Named placeholders in string formatting
(23 answers)
Closed 1 year ago.
So, we all should know that you can include variables into strings by doing:
String string = "A string " + aVariable;
Is there a way to do it like:
String string = "A string {aVariable}";
In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive.

You can always use String.format(....). i.e.,
String string = String.format("A String %s %2d", aStringVar, anIntVar);
I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.

This is called string interpolation; it doesn't exist as such in Java.
One approach is to use String.format:
String string = String.format("A string %s", aVariable);
Another approach is to use a templating library such as Velocity or FreeMarker.

Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,
String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);
results in string containing the following:
A string of ponies.
More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.

Since Java 15, you can use a non-static string method called String::formatted(Object... args)
Example:
String foo = "foo";
String bar = "bar";
String str = "First %s, then %s".formatted(foo, bar);
Output:
"First foo, then bar"

Apache Commons StringSubstitutor can be used.
import org.apache.commons.text.StringSubstitutor;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."
This class supports providing default values for variables.
String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."
To use recursive variable replacement, call setEnableSubstitutionInVariables(true);.
Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"

you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Related

How to insert certain values ​into a string in certain part

I have a special table in my database where I store the message key - value in the form, for example: question first - How are you, ...?
Now I want to insert for example a name at the end of the question. I don't need a hardcode, I want to do it through some formatting. I know that there is an option to insert text through % or ?1 - but I don't know how to apply this in practice. How are you, % or (?1)?
And what if I need to insert text not only at the end, but also in the random parts:
Hey, (name)! Where is your brother, (brothers name)?
You can insert a String into another String using the String.format() method. Place a %s anywhere in the String where you want and then follow the below syntax. More information here.
String original = "Add to this pre-existing String";
String newString = String.format("Add %s to this pre-existing String", "words");
// original = "Add to this pre-existing String"
// newString = "Add words to this pre-existing String"
In your specific situation, you can store the names as other Strings and do this:
String name = "anyName";
String brothers_name = "anyBrotherName";
String formattedString = String.format("Hey, %s! Where is your brother, %s?", name, brothers_name);
How about this?
String.format("Hey, %s! Where is your brother, %s?","Sally", "Johnny");
For using the %, first you will need to create another variable of type string in which you store the text you want to print.
Example:
String a="Alice";
String b="Bob";
String str=string.format("Hey, %s! Where is your brother, %s?"a,b);
System.out.println(str);
Output:
Hey Alice! Where is your brother, Bob?
You can get more information about this here

How to add new text to string without removing old string text?

Suppose I have a string String text = ""; and I add a text to it
text = "Apple";
now I want it not to remove the old String when I add a new one, like this
text = "Banana";
text = "Orange";
The output should be Apple, Banana, Orange, but the output i'm getting is Orange. How to do that in java?
Since String is Immutable then you can't edit t without reassigning it, however there is something called StringBuilder it is mutable so it can be changed.
String original=new String("blabla")
StringBuilder builder=new StringBuilder(myString);
original will not be affected expect if did you re assign it, but because of String builder is mutable you can do something like the following
builder.appened("someData");
and it should be retrieved as string like this
String newString=builder.toString()
You want the variable to hold multiple Strings. Yet, you don't want to append the String. A data structure is what you are looking for.
In this case, ArrayList can fulfill your needs:
ArrayList<String> texts = new ArrayList<String>();
texts.add("Apple");
texts.add("Banana");
texts.add("Orange");
You can get the elemebt by the order you added the Strings with index beggining with 0:
Systen.out.println(texts.get(0)); // prints "Apple"
To print all the elements from the ArrayList:
System.out.println(texts); // prints "Apple, Banana, Orange"
There are 2 ways you can achieve your desired output/result:
1. Using String:
You can simply append the new values at the end of String as following...
String text = "";
text = "Apple";
text = text + ", "+ "Banana";
text = text + ", "+ "Orange";
System.out.println(text); //output will be: Apple, Banana, Orange
2. Using StringBuilder: [recommended]
You can initialize StringBuilder, and use append() function to append new values at the end of the String and at last, you can get String from StringBuilder using toString() method of StringBuilder.
StringBuilder builder = new StringBuilder("");
builder.append("Apple").append(", ").append("Banana").append(", ").append("Orange");
String text = builder.toString();
System.output.println(text); //output will be Apple, Banana, Orange
2nd approach is recommended because when you append a String in StringBuilder, it does not create new object of String in String pool every time, it updates the existing object of StringBuilder.
Whereas String class in Java is immutable, so when you append a String in String literal, then it does update the existing object, it does create new object of String in String pool and points the reference to newly created String pool object.

creating a string by merging an int and a string

I have an int 50 (code calls this value) and a String F (code calls scale). I want to combine them and store a String 50F.
I keep getting a not a statement error.
A few things I have tried:
String new = (value + scale);
String new = value + " " + scale;
String new = value.concat(scale)
Don't use the keyword new as a variable name. Try something like
String str = value + scale;
The Java tutorial on variables states, towards the bottom:
Also keep in mind that the name you choose must not be a keyword or reserved word.
Here are Java's keywords, and new is one of them.
Another Flavor
Code
List<String> totallList = Stream.of(Arrays.asList("50"),Arrays.asList("F"))
.flatMap( string -> string.stream())
.collect(Collectors.toList());
totallList.forEach(System.out::print);
Output:
50F
Note : I solved the question with Java 8 and I know it is a overkill but just another flavor
don't ever use new to define your name variable because new is a reserved keyword

How do I concatenate input in java?

I am trying to concatenate and trying to parse at the same time. I am right now making a excel like program where I can say a1 = "Hello" + "World" and in the cell of A1 have it say HelloWorld. I just need to know how to parse the adding sign and connect those two words. Please tell me if you need more code to understand this, like the runner.
This is my parseInput class :
public class ParseInput {
private static String inputs;
static int col;
private static int row;
private static String operation;
private static Value field;
public static void parseInput(String input){
//splits the input at each regular expression match. \w is used for letters and \d && \D for integers
inputs = input;
Scanner tokens = new Scanner(inputs);
String none0 = tokens.next();
#SuppressWarnings("unused")
String none1 = tokens.next();
operation = tokens.nextLine().substring(1);
String[] holder = new String[2];
String regex = "(?<=[\\w&&\\D])(?=\\d)";
holder = none0.split(regex);
row = Integer.parseInt(holder[1]);
col = 0;
int counter = -1;
char temp = holder[0].charAt(0);
char check = 'a';
while(check <= temp){
if(check == temp){
col = counter +1;
}
counter++;
check = (char) (check + 1);
}
System.out.println(col);
System.out.println(row);
System.out.println(operation);
setField(Value.parseValue(operation));
Spreadsheet.changeCell(row, col, field);
}
public static Value getField() {
return field;
}
public static void setField(Value field) {
ParseInput.field = field;
}
}
This is actually a pretty complicated problem unless you can constrain input to a very small subset of what Excel accepts. If not then you'll probably want to look into something like ANTLR. However, assuming the above input then you'll want to do something like:
Split the string on the equal sign into s1 and s2
Split s2 on the plus sign into s3 and s4.
Trim all the strings, remove the quotes around s3 and s4.
Concatenate s3 and s4 and assign to your datastore indexed by s1.
Depending on how complex your concatenation needs are you can either use string concatenation or a StringBuilder:
result = "" + s3 + s4; // string concatenation
result = new StringBuilder().append(s3).append(s4).toString(); // StringBuilder
Let me know if you have any questions about any of the steps detailed above.
Details on (1) above, assuming input is a1 = "Hello" + "World":
String[] strings = input.split("=");
String s1 = strings[0].trim(); // a1
String s2 = strings[1].trim(); // "Hello" + "World"
strings = s2.split("+");
String s3 = strings[0].trim().replaceAll("^\"", "").replaceAll("\"$", "") // Hello
String s4 = strings[1].trim().replaceAll("^\"", "").replaceAll("\"$", ""); // World
String field = s3 + s4;
String colString = s1.replaceAll("[\\d]", ""); // a
String rowString = s1.replaceAll("[\\D]", ""); // 1
int col = colString.charAt(0) - 'a'; // 0
int row = Integer.parseInt(rowString);
Spreadsheet.changeCell(row, col, field);
I suggest you to implement your custom grammar using a parser generator like JavaCC.
Here you can find a simple tutorial.
I believe this is the better solution because in this way you can handle every expression you need.
Are you sure you want to use all the classes you are using? To parse something like "a=b+c+d.." (assuming you are not trying to validate), easiest and possibly the most efficient way is to use split API in Java lang String
Then join whatever is required using StringBuilder
You need to design and implement a parser and an evaluator. And before that, you need to design the language that your parser/evaluator is going to evaluate.
How to do it.
If your language is really simple, you can get away with parsing it by hand, using something like StringTokenizer to do the tokenization,
Otherwise, you are probably best off learning to use a Java "parser generator" such as JavaCC or ANTLR.
Either way, you need to do some background reading to understand all of the terminology. You could start with Wikipedia and/or the tutorial material from one of the parser generators. Alternatively, there are good textbooks on this topic.
In addition to what Abdullah said, if you really want to save every single ounce of memory you can, you should use the StringBuilder instead of the String concatenation. I believe i read somewhere before that the String concatenation make a new string object for each concatenations while the StringBuilder will add them all to a single String. Shouldn't matter too much though.
In my early life I made an equation evaluator in your style. It cost me huge code and complexity, because of my unawareness about Expression trees. But now with this you will be able to add more capabilities to your parser easily and with native JAVA codes. You will get tons of example of using Expression Trees.

Combine two strings to a single string representing a path [duplicate]

This question already has answers here:
How to combine paths in Java?
(12 answers)
Closed 9 years ago.
I want to combine the strings "test/" and "/go" as "test/go".
How can I do that?
Using only java.io.File the easiest way is to do:
String combined_path = new File("test/", "/go").getPath();
FilenameUtils.normalize() from Apache Commons IO does what you want.
example:
FilenameUtils.normalize("foo/" + "/bar");
returns the string "foo/bar"
As suggested by Jon Skeet here
public static String combine (String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
Append both the strings and replace // with / as below
"test//go".replace("//", "/")
Output: test/go
String test = "test/";
String go = "/go";
String result = test + go.substring(1);
Here's a Guava method that joins an Iterable<String> of items with a char, after trimming all instances of this character from beginning and end of the items:
public static String joinWithChar(final Iterable<String> items,
final char joinChar){
final CharMatcher joinCharMatcher = CharMatcher.is(joinChar);
return Joiner.on('/').join(
Iterables.transform(items, new Function<String, String>(){
#Override
public String apply(final String input){
return joinCharMatcher.trimFrom(input);
}
}));
}
Usage:
System.out.println(joinWithChar(Arrays.asList("test/", "/go"), '/'));
Output:
test/go
This solution
is not restricted to file paths, but to any types of Strings
will not replace any characters found inside the tokens, only trim them from the boundaries
Supposed this is a question related to file names, than take a look at apache-commons-io and its FilenameUtils class
final String test = "test/";
final String go ="/go";
System.out.println(FilenameUtils.normalize(test + go));
output on windows:
test\go
The normalize method will do much more for you, e.g. change '/' to '\' on windows systems.
By the way congrat's to your reputation score by nearly just asking questions :-)
Even simpler:
"test/" + "." + "/go"

Categories