I am using a set of constant Strings for text anonymization. One of the strings should go something like "[Town in the state of XX]", where XX is to be replaced later with an actual state (the rest of the string remains as is).
My question is: is there a way to do this "elegantly" (in the spirit of a SQL PreparedStatement)?
Or should I just put XX and then do myString.replace("XX", "someState"), in which case, the string can no longer be a constant :(
EDIT: Just realized that String.replace returns a new String, so myString could still be a constant with this method.
If you use %s instead of XX, then you can simply use String.format.
You can use the Formatter class
And conveniently from system out
System.out.format("My name is '%s' and i am %d years old. My party will be at '%s'.", name, years, time);
Related
This question already has answers here:
String valueOf vs concatenation with empty string
(10 answers)
Closed 5 years ago.
I want to know the difference in two approaches. There are some old codes on which I'm working now, where they are setting primitive values to a String value by concatenating with an empty String "".
obj.setSomeString("" + primitiveVariable);
But in this link Size of empty Java String it says that If you're creating a separate empty string for each instance, then obviously that will take more memory.
So I thought of using valueOf method in String class. I checked the documentation String.valueOf() it says If the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So which one is the better way
obj.setSomeString("" + primitiveVariable);
obj.setSomeString(String.valueOf(primitiveVariable));
The above described process of is done within a List iteration which is having a size of more than 600, and is expected to increase in future.
When you do "" that is not going to create an Object. It is going to create a String literal. There is a differenc(How can a string be initialized using " "?) actually.
Coming to your actual question,
From String concatenation docs
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
So unnecissarly you are creating StringBuilder object and then that is giving another String object.
However valueOf directly give you a String object. Just go for it.
Besides the performance, just think generally. Why you concatenating with empty string, when actually you want to convert the int to String :)
Q. So which one is the better way
A. obj.setSomeString(String.valueOf(primitiveVariable)) is usually the better way. It's neater and more domestic. This prints the value of primitiveVariable as a String, whereas the other prints it as an int value. The second way is more of a "hack," and less organized.
The other way to do it is to use Integer.toString(primitiveVariable), which is basically the same as String.valueOf.
Also look at this post and this one too
I'm new to code in Android Studio and when i set a integer in a text like this:
textview.setText(String.format("%d",1));
This code give me back a warning:
Implicitly using the default locale is a common source of bugs: Use String.format (Locale,...)
What is the correct code for put an integer in a .setText?
I founded more question on stackoverflow but don't apply to this.
What is the correct code for put an integer in a .setText?
You simply need to convert your int as a String, you can use Integer.toString(int) for this purpose.
Your code should then be:
textview.setText(Integer.toString(myInt));
If you want to set a fixed value simply use the corresponding String literal.
So here your code could simply be:
textview.setText("1");
You get this warning because String.format(String format, Object... args) will use the default locale for your instance of the Java Virtual Machine which could cause behavior change according to the chosen format since you could end up with a format locale dependent.
For example if you simply add a comma in your format to include the grouping characters, the result is now locale dependent as you can see in this example:
System.out.println(String.format(Locale.FRANCE, "10000 for FR is %,d", 10_000));
System.out.println(String.format(Locale.US, "10000 for US is %,d", 10_000));
Output:
10000 for FR is 10 000
10000 for US is 10,000
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
hiding strings in Obfuscated code
I'm trying to hide a little some static Strings of my app in order to make it harder to decompile, this way like the constants like cipher algorithms names are harder to find in the obfuscated code.
I've considered things like:
String CONCAT= "concat"+"string";
String RAW_STRING= "raw_string";
String FROM_BYTES=new String("from_bytes".getBytes());
String FROM_CHARS=new String(new char[]{'f','r','o','m','_','c','h','a','r','s'});
String FROM_CHAR2=new String(new char[]{102,114,111,109,95,99,104,97,114,115,95,50});
And the last two options seems to be "darker" than the raw option but I imagine there are better ways for doing this.
How can I improve this? Thanks
For one, you shouldn't just write
String FROM_CHAR2=new String(new char[]{102,114,111,109,95,99,104,97,114,115,95,50});
It's a dead give-away that the char array is actually a String.
You can do a combination of the followings:
put your "String" in an int[] array
or even better, break your String into several int arrays
calculate/manipulate the array's values at various stage of the application, so its value will only become valid at a certain interval during a runtime, guaranteeing that it won't be deciphered at a curious glance by decompiling your code
passes the array(s) back and forth, through local variables, back to instance variables, etc, before finally converting the arrays to a single array to be passed to the String constructor
immediately set the String to null after use, just to reduce the amount of time the actual String exist at runtime
I would prefer to set the value in the static (class) initializer using an decryption algo
Something like
class ...
String CONCAT;
static {
CONCAT = uncrypt ("ahgsdhagcf");
}
where uncrypt might be really a good unencryption algo or somewhat weaker a base64 decode.
In any case you need a simple program to encode your string first.
what type could contain a number like 2023209999 in java?
do you think that using a string type to represent a telephone number is a good idea?
Using a string is a very good idea. Remember that the point of OOP is that different types of data have different usage patterns. So let's look at a phone number patterns.
Do we add phone numbers or perform other arithmetic on them?
Do we split it based on length, match against parts of it, replace parts of it?
The answer to the first question is no. So we don't manipulate them like numbers. The answer to the second question is yes, so we manipulate them like strings.
Now, many here are advocating making phones a class by itself. There is merit in this regard, but I'm addressing the more pressing concern of how do you store the phone number, which is something you need to do no matter if a phone is a class or not. A phone class which stored its data as a number would not be a good fit.
I would write a PhoneNumber class, which uses String as an underlying storage, and adds validation / pretty formatting functionality.
I'd say a String at the least, but personally, I'd make a PhoneNumber object. It's the sort of thing that affords itself to extra methods such as:
boolean isValid();
PhoneNumberUtils.getCountry(PhoneNumber number);
PhoneNumberUtils.getState(PhoneNumber number);
...or whatever. One thing I'd be thinking out for is just letting people put in phone numbers and getting the system to learn the rest. I despise entering data that could be determined by the system. This is just my preference.
On a simpler level, just encapsulating the String in an PhoneNumber object gives your brain a handle ... in a week or so when your brain wonders "Where should this phone number method go?", you may find yourself with a quick answer.
I think that a dedicated PhoneNumber class is the way to go about it. Phone number are not just strings. First and foremost, phone numbers obey to rules, such as: they only contain digits, in the US they can contain either 7 or 10 digits. You'd need a constructor to make sure that your phone numbers are correct.
Second, a class will make it easy for you to steamline the differences between various formats. For instance, 555-4834 and 5554834 are different strings but are the same phone number.
Finally, you'd probably want methods such as: getAreaCode() or getLocalNumber() Calling such a method is much more concise and much less error prone than manipulating a String directly:
String phoneNumber pn = ....;
String localNumber = pn.length() == 7 ? pn : pn.substring(4) :
it's rather late, but I may add my 2 cents ....
I am in telecom and have made best experience to store phone numbers in structures (or objects) with character members of variable length, i.e.
struct TelephoneNumber (
InternationalPrefix VARCHAR;
AreaCode VARCHAR;
Subscriber VARCHAR;
Extension VARCHAR;)
I never store access digits (the zero's, double zeros, pluses etc.), they don't belong to to the telephone number per se but are part of what I may call "dialing rules"
struct DialingRule (
International VARCHAR;
National VARCHAR;
Local VARCHAR;)
typical values for DialingRule are "00", "0", NULL for a direct line, and "000", "00", "0" for a PBX requiring a "0 to get the line"
to "display" a number you can freely format the objects, insert hyphens, brackets or whatever you fancy
to create a dialable sequence I determine the type (international, national or local) by comparing the corresponding elements of the FROM and TO number and add the respective string from the dialing rule set as a prefix.
This all may sound like an overkill, but for international applications with strong requirements on data integrity and with strong links to hardware I didn't come up with any better. It removes ambiguities and the need for hardcoding lenghts etc. when you want to manipulate numbers. It's also easy to prefill parts of the structure from country / city lookup tables containing ISO country codes, IATA city codes and their corresponding prefixes.
Good luck
MikeD
In Germany area codes start with a 0 so a integer representation would lose that information.
Still I wouldn't recommend just using a String.
Instead use a Phonenumber class (or interface and implementations). This approach has some advantages.
If at some point you find that a String is insufficient you just have to change the Phonenumber class not every class that uses Phonenumbers.
Additionally it would allow you to seperate area code and number internally.
If you need to record leading 0 or + for international then you should use a String.
If you ain't worried about these you can just use a long. e.g.
long phoneNumber = 2023209999L; // the L is for a long constant.
It would honestly come down to what you plan to do with it. If you just want to store it to reprint it a string or maybe even a long would be fine, assuming we are dealing with US numbers.
If you want to do something more sophisticated making a Class with containing several strings, one for each component.
Basically just not enough info here to make a real decision.
Using a String Type allows you to break apart the phone number without any voodoo or casting.
For instance, if you change the format of how you accept phone numbers, you'll have to do extra work to get the phone number contatenated if it is a long instead of a string.
Another thing to consider: an int would be too small. the maximum value an int can hold is 2,147,483,647. as far as primitives are concerned, long is your best bet.
It depends on what you're doing. Let's say you want to be able to represent international numbers, local numbers, branch exchange numbers, etc. In this case, a String is a bad choice. It doesn't have any meta-information. You probably want a class to represent a phone number.
As far as what you use to represent the phone number in this class, you could use a BigInteger (to allow you to have international numbers), or more simply, you could store each portion of a phone number as a long.