how to remove a part of a string - java

Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). You may assume that the remove string is of length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"
Why can't I use this code:
public String withoutString(String base, String remove)
{
base.replace(remove, "");
return base;
}

base.replace doesn't change the original String instance, since String is an immutable class. Therefore, you must return the output of replace, which is a new String.
public String withoutString(String base, String remove)
{
return base.replace(remove,"");
}

String#replace() returns a new string, doesn't change the one it is invoked on, since strings are immutable. Use this in your code:
base = base.replace(remove, "")

Update your code:
public String withoutString(String base, String remove) {
//base.replace(remove,"");//<-- base is not updated, instead a new string is builded
return base.replace(remove,"");
}

Try following code
public String withoutString(String base, String remove) {
return base.replace(remove,"");
}
For Input :
base=Hello World
remove=llo
Output :
He World
For more on such string operations visit this link.

Apache Commons library has already implemented this method,you don't need to write again.
Code :
return StringUtils.remove(base, remove);

Related

Is there any method in ObjectMapper to match json string with Enum

I have an Enum
public enum status{
YES,
NO
}
the input from json string is "Yes" or "No", is there any method in ObjectMapper to match status.YES with "Yes", and status.NO with "No".
I don't want to change enum, because int my previous system, people use the enum all the time, I don't want cause problem for others
You can always redefine it like:
public enum Status {
YES("Yes"),
NO("No");
private final String status;
private Status(final String status) {
this.status = status;
}
public String value() {
return this.status;
}
}
And then use something like this: Status.YES.value();
You can use toString() method available in all Java enums:
http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html
and on returned String call compareToIgnoreCase method to compare it with input:
http://www.tutorialspoint.com/java/java_string_comparetoignorecase.htm
Or you can call toUpperCase on input String and then comapre them:
http://www.tutorialspoint.com/java/java_string_touppercase.htm
Finally, you can use toString mentioned earlier and put all letters except the first to lower case:
String YesString = enumWithYESValue.toString().substring(0, 1) + enumWithYESValue.toString().substring(1).toLowerCase();
Based on: How to capitalize the first letter of a String in Java?

replace String with value of properties file in java

I have a code to replace stream of string. I need to search a specific string that is defined in the key of properties file
String result="";
int i=0;
while (i<listToken.size()){
result = listToken.get(i);
while (enuKey.hasMoreElements()) {
String key = (String)enuKey.nextElement();
// String value = propertiesSlang.getProperty(key);
if (listToken.get(i).equals(key)){
String value = propertiesSlang.getProperty(key);
listToken.get(i).replace(listToken.get(i), value);
System.out.print("detected");
}
}
i++;
}
But it doesn't replace word. How I can replace words using properties.
It's because you forgot to assign the result, using the method set():
listToken.set(i, propertiesSlang.getProperty(key)));
assuming listToken implements AbstractList
Why complicate things with replace(). As far as I understand your code you can simply do -
String value = propertiesSlang.getProperty(key);
listToken.set(i, value);
I see you have modified your code again to
listToken.get(i).replace(listToken.get(i), value);
Just so that you know String class is immutable. So operations like replace() or substring() will give you a new String and not modify the original one. Get the new String and set it in your list listToken.

Howto convert the value of a hashmap to String i Java

I have a HashMap. I am trying to retrieve the value and print it using the key from the user-code.
The code is:
lib.addbook(book2.getISBN(), book2);
Book ret = lib.getbook("978-81-291-1979-7");
System.out.println(ret);
Current Output:
O/P: LibraryPackage.Book#527c6768
I want the output to be a string and to display the actual value not the address of the book.
You have to implement (and override) the toString() method in your Book class, and specify what you want the output to be. E.g.:
#Override
String toString()
{
return this.author+": " + this.title;
}
commons-lang has a great utility for this if you don't want to override the .toString() method, or need to represent it differently in different situations:
Here's a call to build a string based on reflection:
String str = ToStringBuilder.reflectionToString(object);
In fact, this is a great way to implement the .toString() method itself. Another alternative use of this class would be a field by field creation of the string:
String str = new ToStringBuilder(object)
.append("field1", field1)
.append("field2", field2)
.toString();

take the value of enum and covert it to String

I should take from a variable enum its value and transform it to string.how can i do?
here it is the type enum:
public enum State{
b,c,p;
};
now i have to insert into an object String one value.
You might use enum.name orenum.toString to get the name of the enum constant, or enum.ordinal to get the ordinal position.
you can use name() or toString(), so :
State aState = State.c;
String strState = aState.name();
See here the official java reference for more information...
State.b.toString() will return "b". The same goes for the other ones.
Usually,
State state = ...;
String string = state.toString();
should work, but it is not recommended since someone might override toString for some other purpose.
Instead the method you are looking for is
String string = state.name();
As an aside, your enumerated stated should always be all in capitals, and they should have descriptive names. It's not a language rule, but a convention. For example enum State { ON, OFF, PAUSED; }.
I tend to do something more complicated, but I find that it's more flexible:
public enum MyEnumeration {
SOME_NAME("Some Name"),
OTHER_THING("Other Thing"),
...
MORE_VALUES("More Values"),
private final String displayName;
private MyEnumeration(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
This way, I use standard capitalization for my enums in code, but can have a more presentable name for them.
This trick can also be used to replace ordinal, by initializing a number, and then you don't need to worry about rearranging your enums.
Method #1: Using the built-in toString() and name() methods
If you want to print a String that is the same as the value of the State, then you can use the toString() method, or the name() method.
System.out.println(State.b); // Prints "b"
System.out.println(State.c); // Prints "c"
System.out.println(State.p); // Prints "p"
Method #2: Using a constructor to create a custom mapping
If you want to have a custom String associated with each of those states, you can use a constructor to associate a particular value with each enum value:
public enum State{
b("State B"), c("State C"), p("State P");
private String longName;
private State(String longName) {
this.longName = longName;
}
#Override
public String toString() {
return this.longName;
}
};
Of course, if you don't want to break the default toString() usage, you can create a different method called getFullName(), for example, to return the custom value.

Do I need to do something special to use the replace method with symbols?

Here's some code
private String replaceToEncrypt(String password) {
password.replace('A','#');
password.replace('E','=');
password.replace('I','!');
password.replace('J','?');
password.replace('O','*');
password.replace('P','#');
password.replace('R','&');
password.replace('S','$');
}
Using print statements its seems that nothing happens because ABCDEFGHIJKLMNOPQRSTUVWXYZ
before this method is ABCDEFGHIJKLMNOPQRSTUVWXYZ after
Thanks
You have to re-assign the result of each replacement, for example:
password = password.replace('A','#');
This is because all Strings in Java are immutable, and any operation that modifies a String what really does is return a new String with the modifications, the original String is kept unchanged.
replace() according to the Java 7 API:
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
So in your code you need to reassign to password the new String:
password = password.replace('A','#');
//etc...

Categories

Resources