Formatting string in Java - java

Hi I'm new to java so this is going to seem a bit tame. Anyway, in objC, when I want to insert a variable into a string, I would do it like this:
NSString *string = [NSString stringWithFormat:#"test%i", variable];
How do I do this in java?

There are number of ways, but the java.lang.String.format() method is an easy one:
String message = String.format("There are %d ways to leave your lover", 50);

Using the String.format() method. Take a look at the documentation for understanding all the different formatting options available.

Related

Build code by using Concatenation?

Is there a way i can create code build code by using Concatenation in Android studio/eclipse?
In other words i have 2 sets of strings one for each country i am dealing with ZA and KE. They have 2 different EULA's.
So i would like to pull the string related to the respective country.
String message = mContext.getString(R.string.eula_string_za);
above is an example of the output code. is there someway i can go about "creating" that based on If statements?
String str = "mContext.getString(R.string.eula_string_";
if (something = "ZA") {
str += "za);";
} else {
str += "ke);";
}
so if the country selected is ZA then the output code should be
mContext.getString(R.string.eula_string_za);
and if its KE it should be
mContext.getString(R.string.eula_string_ke);
and then the result will then pull the correct string from strings.xml?
Java is a compiled code, not an executed one,you can't write code this way like in an interpreted language.
The best way to manage different languages in android is to use a string.xml file for each language.
Take a look at this tutorial, it will help you a lot :
Supporting different languages in android
If you want to go this route you could try to use reflection. Have a look at Class.getField(…) if you want to use reflection.
Instead of first building a code string using a if statement you can also use the same if statement to find the correct string:
String str;
if (something.equals("ZA")) {
str = mContext.getString(R.string.eula_string_za);
} else {
str = mContext.getString(R.string.eula_string_ke);
}
Note that your condition something = "ZA" does not do what you think it does: It assigns something the string "ZA" and then evaluates itself to "ZA", so this would not even compile. The correct way would be something == "ZA", but even this does not work in the general case. You need to use String.equals(…). Some even argue you should use it the other way around (i.e. "ZA".equals(something)) to avoid a NullPointerException…
Another possibility would be to first build a Map from county to the corresponding string ID for all the EULAs you have and then asking the Map to return the correct one.
But probably the cleanest solution would be to use Androids built in mechanism, as hkN suggests.

Format specific section of String

I have a String: a%sb%sc%s. I need to format b before I format a or c, but I'm not sure how or even if I can specify only to format b while keeping the rest of the String unformatted.
In other words, I'm trying to do this:
String.format(foo, "test");
With the outcome:
a%sbtestc%s
Is it possible to manipulate a String like this or should I just use String.replace instead?
A little more detail. The ultimate String will look something like: aA-PARMbB-PARMcC-PARM and then used to fetch some data. a and c are much more dynamic than b, so I'm trying to format b before hand.
So, again. I'm trying to achieve the following:
String.format(foo, "B-PARM");
With the results:
a%sbB-PARMc%s
Then format the rest:
String.format(formattedFoo, "A-PARM", "C-PARM");
You could do your formatting in steps,
String aString = String.format("something %s something else", "a string");
String bString = String.format("...%s...", "test");
String cString = // ....
String completeString = String.format("a%sb%sc%s", aString, bString, cString);
but again, I have to wonder what is going on, and whether this represents an XY Problem, one that is best solved by a completely different approach. Consider giving us the details of the overall problem that you're trying to solve and perhaps not the code tactics that you're using to try to solve it.

Advantages of format over concatenation

I'm using Java, and I was wondering if there is any advantage to using format over simple concatenation.
I would either format like this:
a = String.format("%s/hi", b);
or like this:
a = (b + "/hi");
Is there any advantage (other than cleanliness) of using one over the other?
It is better practice to use String.format over String.concat.
String.format() is more than just concatenating strings. For example, you can display numbers is a specific locale using String.format().
However, if you don't care about localization, functionally, there is no difference. Maybe one is faster than the other, but in most cases it will be negligible.
Format can handle quite complex patterns and formatting, if you need them. I would personally go for readability over any perceived "performance" benefits for anything other than code used in a large loop. Who cares if your method creates a couple of objects that get garbage collected soon afterwards anyway?
Only one String will be created in the following line,
a = String.format("%s/hi", b);
More than One String is being created in the following line
a = (b + "/hi");

Coverting string to java code

I have a string constructed at run time like
str = "a+dataValue(i)";
where 'a' is a variable, 'dataValue(i)' is a function with argument i
Now I have a function where I want to use string str as part of code. For example
public void func()
{
for(int i=0;i<n;i++)
Sytem.out.println(converted_to_java_source(str)); //(i.e.) a+dataValue(i); it should be converted at runtime not compile time
}
I need output like as follows:
when a = 2; dataValue(i) returns i; n = 5
On call to func it should print
2 3 4 5 6 7
Thank you.
You are looking for the Java equivalent of the eval function / method in dynamically typed languages like JavaScript, Perl, Python and so on. Unfortunately there isn't one.
There are various ways to do this kind of thing in Java, but they are all expensive, and come with a variety of other down-sides.
My advice is to look for another (easier / cheaper) way to meet your requirement.
If you really need to go down the eval route, then here are some related Q/A's which give a reasonable coverage of the options.:
Is there an eval() function in Java?
Is there a java equivalent of the python eval function?
You could take a look at the Byte Code Engineering Libraray (BCEL) or ASM. In either case, things can get messy and overcomplicated so I would recommend what Stephen suggested and try to look for another way.
You could, for instance, use som if else statements to call your function in the usual manner, maybe something like:
String functionName = "...";
if (functionName.toLowerCase().equals("someMethodName")
{
someMethodName(someParams);
}

What ways can you create a string with 2000 "spaces"

For various reasons I am trying to set a string to 2000 spaces. Currently I am using:
String s = String.format("%1$-2000s"," ");
This is great for Java 5, however, some of the developers in our department are using 1.4 and this does not work.
I was wondering, are any other ways of achieving the same result? I know I can do things like a for loop adding a space at a time, but I am looking for something simple like the format option.
For those that may be interested in why I need this, it is because we have an XML type on a dataobject that on insert into the DB is null. It then gets updated with the XML string, usually around 2000 characters in size. In Oracle pre-reserving this space can prevent row migration, therefore, increasing performance.
Thanks!
char[] spacesArray = new char[2000];
Arrays.fill(spacesArray, ' ');
String spaces = new String(spacesArray);
the simplest answer: (scroll to see all the codes)
String s = " "; // 2000 spaces
You can use lpad(' ',2000,' ') in the insert statement directly to tell Oracle to create the value you want.
In fact, you can set the field in question to have this as the default, which could prevent you from needing to change it in multiple places (if your code is explicitly sending null as the value for the field, that will override the default).
A StringBuffer and then add a space 2000 times in a loop, and toString() afterwards. I don't think there are any "simpler" ways to do it which doesn't end up doing this anyway under the covers.
If you do this a lot, it would make a good library function.
A random function I found in my personal library:
public static String whiteSpace2(int l) {
if (l==0) return "";
String half=whiteSpace2(l/2);
if ((l&1)!=0) {
return half+" "+half;
} else {
return half+half;
}
}
Not claiming it is the fastest possible way to generate whitespace, but it works :-)
StringUtils.repeat(" ", 2000) (from commons-lang)
However, I'm not sure whether such micro-optimizations should be made with the cost of code that would require a 5 line comment to explain why is this needed. If you do it - be sure to add an extensive comment, otherwise imagine the reaction of those reading your code.
If nothing else works:
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 2000; ++i)
sb.append(" ");
String str = new String(sb);
See this other question.
Can I multiply strings in Java to repeat sequences?
Both Apache Commons StringUtils and Google Guava libraries have commands to multiply (repeat) strings.

Categories

Resources