This is actually an exercise from CodingBat. The definition of the problem is as follows:
Given a string, if the string "del" appears starting at index 1, return a string where that "del" has been deleted. Otherwise, return the string unchanged.
delDel("adelbc") → "abc"
delDel("adelHello") → "aHello"
delDel("adedbc") → "adedbc"
My work is as follows:
public String delDel(String str) {
String del = "del";
if (str.indexOf(del, 1) == 1){
str.replaceFirst("del", null);
}
return str;
}
It works fine for most of the cases, but I get NullPointerException in "adelbc", "adelHello" and "adel" cases. I can't quite understand why.
If you look closely in the OpenJDK sources, you'll note that replaceFirst delegates work to the regexp functions, including this one for replacing step:
public String replaceFirst(String replacement) {
if (replacement == null)
throw new NullPointerException("replacement");
reset();
if (!find())
return text.toString();
StringBuffer sb = new StringBuffer();
appendReplacement(sb, replacement);
appendTail(sb);
return sb.toString();
}
Note that replacement can not be null. I assume the behaviour is going to be similar in other implementations of the JRE. Please use "" - empty string - instead of null as the replacement.
Also as mentioned in the comments by cricket_007 you want to save the result of replaceFirst for returning, since the original string will not be affected (all Strings in Java are immutable). The final piece of code:
public String delDel(String str) {
String del = "del";
if (str.indexOf(del, 1) == 1){
return str.replaceFirst("del", "");
}
return str;
}
Related
As a novice Java programmer who barely got started in Java programming, I am totally exhausted in trying to find a solution to this issue. A course that I am currently studying gave homework that asked me to create a Java class that has a sort of “reverse” method that returns a new version of the string
of the current string where the capitalization is reversed (i.e., lowercase to uppercase
and uppercase to lowercase) for the alphabetical characters specified in a given condition. Say if I were to reverse “abc, XYZ; 123.” using reverse("bcdxyz#3210."), it must return "aBC, xyz; 123.". (P.S: the class ignores numbers and special characters and the variable "myString" is where the "abc, XYZ; 123." goes to.). So far, I've only managed to return out "aBC, XYZ; 123." with the code below. Am I missing something here?
public String reverse(String arg) {
// TODO Implement method
String arg_no_sym = arg.replaceAll("[^a-zA-Z0-9]","");
String arg_perfect = arg_no_sym.replaceAll("\\d","");
if (myString != null) {
char[] arrayOfReplaceChars = arg_perfect.toCharArray();
char[] arrayOfmyString = myString.toCharArray();
for (int i = 0; i < arg_perfect.length(); i++) {
myString = myString.replace(String.valueOf((arrayOfReplaceChars[i])), String.valueOf((arrayOfReplaceChars[i])).toUpperCase());
}
return myString;
}
else {
return "";
}
}
How about using the methods isUpperCase() and isLowerCase() to check the case of the letters and then use toUpperCase() and toLowerCase() to change the case of them?
I am trying to duplicate backslash characters inside a string.
The string is a directory path!
I wrote a function, but it doesn't return a correct result!
When I tested the function with
C:\Users\Asus i7\Desktop\untitled1ghthr\src\sample\panda.mp3
it returns
C:\\User\s\Asus \i7\Desk\top\untitled1g\hth\r\src\\sample\panda.mp3
While i want it to return
C:\\Users\\Asus i7\\Desktop\\untitled1ghthr\\src\\sample\\panda.mp3
Code of the function
public StringBuffer add(String ch) {
StringBuffer str = new StringBuffer(ch);
for(int i=0;i<ch.length();i++){
if (ch.charAt(i)=='\\'){
str.insert(i, '\\');
}
}
return str;
}
Consider using Paths.get : documentation
The method you are trying to use will not work on all OS.
So I am working on a project in java and I have just a quick question.
I have a method that is receiving a string and I want to strip out the spaces and check that is is not empty. So far I have the below in place however it doesn't seem to be working properly.
public static Boolean isValid(String s) {
s.replace(" ", "");
if (s == ""){
return false;
}
else {
return true;
}
}
Any help would be appreciated :)
Ta
You can try with this:
public static Boolean isValid(String s) {
return (!s.trim().isEmpty());
}
First you have forgot the assignment for s.replace(" ",""). Store that in a variable, e.g.
x = s.replace(" ","");
For string comparison use .equals() method instead of ==
You can use the following code as well :
newString=myString.replaceAll("\\s+","");
This removes one or more spaces in between Strings as well as leading and trailing whitespaces
Use : myString.trim() to remove only leading and trailing whitespaces
and then newString.isEmpty()
You should use .equals() to compare Strings
When you're comparing strings, use .equals().
Its only in artihmetic expressions you use the == sign
TO check whether your string is empty use the .isEmpty() function
You forgot the assignment:
s = s.replace(" ", "");
EDIT:
for the comments stating that == is not working. I wanted to say that it does work for Java 7
replaceAll() method supports regular expressions as well as isEmpty() is already there in String class so we can reuse it and is safer to use here.
simply use like this:
public static Boolean isValid(String s) {
s = s.replaceAll("\\s", "");
if (s.isEmpty()) {
return false;
}
else {
return true;
}
}
Difference between equals and == incase of String comparison is well explained in the thread
value of s.replace() should be assigned to itself or some other variable.
I have very long strings that need to have a pattern removed if it appears. But it's an incredibly rare edge case for it to appear in the strings.
If I do this:
str = str.replace("pattern", "");
Then it looks like I'm creating a new string (because Java strings are immutable), which would be a waste if the original string was fine. Should I first check for a match, and then only replace if a match is found?
Short answer
Checking the documentation of various implementations, none seems to require the String.replace(CharSequence, CharSequence) method to return the same string if no match is found.
Without the requirement from the documentation, the implementation may or may not optimize the method in the case no match is found. It is best to write your code as if there is no optimization, to make sure that it runs correctly on any implementation or version of JRE.
In particular, when no match is found, Oracle's implementation (version 8-b123) returns the same String object, while GNU Classpath (version 0.95) returns a new String object regardless.
If you can find any clause in any of the documentation requiring String.replace(CharSequence, CharSequence) to return the same String object when no match is found, please leave a comment.
Long answer
The long answer below is to show that different implementation may or may not optimize the case where no match is found.
Let us look at Oracle's implementation and GNU Classpath's implementation of String.replace(CharSequence, CharSequence) method.
GNU Classpath
Note: This is correct as of the time of writing. While the link is not likely to change in the future, the content of the link is likely to change to a newer version of GNU Classpath and may go out of sync with the quoted content below. If the change affects the correctness, please leave a comment.
Let us look at GNU Classpath's implementation of String.replace(CharSequence, CharSequence) (version 0.95 quoted).
public String replace (CharSequence target, CharSequence replacement)
{
String targetString = target.toString();
String replaceString = replacement.toString();
int targetLength = target.length();
int replaceLength = replacement.length();
int startPos = this.indexOf(targetString);
StringBuilder result = new StringBuilder(this);
while (startPos != -1)
{
// Replace the target with the replacement
result.replace(startPos, startPos + targetLength, replaceString);
// Search for a new occurrence of the target
startPos = result.indexOf(targetString, startPos + replaceLength);
}
return result.toString();
}
Let us check the source code of StringBuilder.toString(). Since this decides the return value, if StringBuilder.toString() copies the buffer, then we don't need to further check any code above.
/**
* Convert this <code>StringBuilder</code> to a <code>String</code>. The
* String is composed of the characters currently in this StringBuilder. Note
* that the result is a copy, and that future modifications to this buffer
* do not affect the String.
*
* #return the characters in this StringBuilder
*/
public String toString()
{
return new String(this);
}
If the documentation doesn't manage to persuade you, just follow the String constructor. Eventually, the non-public constructor String(char[], int, int, boolean) is called, with the boolean dont_copy set to false, which means that the new String must copy the buffer.
589: public String(StringBuilder buffer)
590: {
591: this(buffer.value, 0, buffer.count);
592: }
245: public String(char[] data, int offset, int count)
246: {
247: this(data, offset, count, false);
248: }
594: /**
595: * Special constructor which can share an array when safe to do so.
596: *
597: * #param data the characters to copy
598: * #param offset the location to start from
599: * #param count the number of characters to use
600: * #param dont_copy true if the array is trusted, and need not be copied
601: * #throws NullPointerException if chars is null
602: * #throws StringIndexOutOfBoundsException if bounds check fails
603: */
604: String(char[] data, int offset, int count, boolean dont_copy)
605: {
606: if (offset < 0)
607: throw new StringIndexOutOfBoundsException("offset: " + offset);
608: if (count < 0)
609: throw new StringIndexOutOfBoundsException("count: " + count);
610: // equivalent to: offset + count < 0 || offset + count > data.length
611: if (data.length - offset < count)
612: throw new StringIndexOutOfBoundsException("offset + count: "
613: + (offset + count));
614: if (dont_copy)
615: {
616: value = data;
617: this.offset = offset;
618: }
619: else
620: {
621: value = new char[count];
622: VMSystem.arraycopy(data, offset, value, 0, count);
623: this.offset = 0;
624: }
625: this.count = count;
626: }
These evidences suggest that GNU Classpath's implementation of String.replace(CharSequence, CharSequence) does not return the same string.
Oracle
In Oracle's implementation String.replace(CharSequence, CharSequence) (version 8-b123 quoted), the method makes use of Pattern class to do the replacement.
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
Matcher.replaceAll(String) call toString() function on CharSequence and return it when no match is found:
public String replaceAll(String replacement) {
reset();
boolean result = find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
appendReplacement(sb, replacement);
result = find();
} while (result);
appendTail(sb);
return sb.toString();
}
return text.toString();
}
String implements the CharSequence interface, and since the String passes itself into the Matcher, let us look at String.toString:
public String toString() {
return this;
}
From this, we can conclude that Oracle's implementation returns the same String when no match is found.
I have not found a definitive answer (from the docs), but I tried this out on Oracle's JRE7 and found that replace returned a reference to the same string.
Here is the code I used for testing:
public class NoReplace {
public static void main(String[]args) {
String a = "hello";
/* Test: replacement with no match */
String b = a.replace("X", "H");
/* a and b are still the same string? */
System.out.println(b == a); // true
/* Sanity: replacement WITH a match */
String c = a.replace("h", "H");
/* a and c are still the same string? */
System.out.println(c == a); // false
}
}
But I'd be interested in seeing some benchmarks of replace vs contains to know for sure if there's any advantage.
Ok.. In Java 8. This is what happens when you call myString.replace().
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this)
The target String is compiled as a Literal pattern. and matcher() is called on it by passing the calling stringInstance to it.
Now the matcher() method will return a new matcher here. Just note that the text field of the matcher will be the current object (this) i.e the String object on which replace() was called.
Next, in replaceAll() we have the following code :
boolean result = find();
i.e.,
public String replaceAll(String replacement) {
reset();
boolean result = find(); --> returns false.
if (result) {
StringBuffer sb = new StringBuffer();
do {
appendReplacement(sb, replacement);
result = find();
} while (result);
appendTail(sb);
return sb.toString();
}
return text.toString(); --> same String
}
if `find()` returns false, then ,matcher.text is returned which is the original String
I need a advice (both in java & .net) for the following piece of code.
public void method(bool value)
{
String someString;
//some code
if (value)
{
//some code
...
someString = "one" + value;
}
else
{
//some code
...
someString = "two" + value;
}
}
Which one is advisable and why? either code like above or code like
someString = "onetrue";
someString = "twofalse";
After compilation and optimization by JDK, method will look like:
public static String method(boolean value) {
String someString;
if (value) {
StringBuilder sb = new StringBuilder();
sb.append("one");
sb.append(value);
someString = sb.toString();
} else {
StringBuilder sb = new StringBuilder();
sb.append("two");
sb.append(value);
someString = sb.toString();
}
return someString;
}
If this code is invoked very frequently, it could bring a performance impact, compared to the second version. In each case a new StringBuilder is constructed and three methods are invoked on it. And boolean should be converted to an object before calling append. While in the second version we just return constant. Everything depends on how often this code is called.
Neither will make any difference it's purely style.
Since you have // some other code I'd just stick with the first. If you only had one line in each branch then either is ok.
At a high level they both are the same but if you look down at lower levels, I would advise to using the method:
someString = "onetrue";
someString = "twofalse";
This is because when you do "one" + value, the value is actually a bool and the toString() method of the bool object will be called to add to the string. Basically just adding another step opposed to just specifying what to add to the string.