How to duplicate backslash character in a String? - java

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.

Related

Better way to invert cases of characters in a string in Java

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?

How does the replaceAll java method work?

I'm trying to figure out how the str.replaceAll(string, newString) method works. I know how to use it, but I'm trying to figure out what goes on inside the method. Does it use multiple for loops and strings, or something more advanced than that? Ideas, pseudocode, and code examples would be lovely.
PS I've already searched this up, but it only shows how to use it, not how it works.
According to the source code for String#replaceAll:
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
It creates a Pattern and uses regex to replace the target with the replacement.
In case you want to know about the Matcher#replaceAll call:
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();
}

Deleting A Specified Substring in Java

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;
}

Java: Validating a string

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.

Search a string against another using Regex

I need to check whether a String is contained in another String.
For example, "abc" is contained in "abc/def/gh","def/abc/gh" but not in "abcd/xyz/gh","def/abcd/gh".
So, I have split the input String by "/". Then iterated the generated String array to check against the input.
Is it possible to avoid the creation of the array using something like Regex?
Also, could anybody confirm whether using Regex will be faster than the creation & iteration of array as I have used?
Thanks in advance
public class RegexTest {
public static void main(String[] args) {
System.out.println(contains("abc/def/gh", "abc"));
System.out.println(contains("def/abc/gh", "abc"));
System.out.println(contains("def/abcd/gh", "abc"));
System.out.println(contains("abcd/xyz/gh", "abc"));
}
private static boolean contains(String input, String searchString) {
String[] strings = input.split("/");
for (String string : strings) {
if (string.equals(searchString))
return true;
}
return false;
}
}
The console output is:
true
true
false
false
Something like this:
String pattern = "(.*/)?abc(/.*)?";
System.out.println("abc/def/gh".matches(pattern));
System.out.println("def/abc/gh".matches(pattern));
System.out.println("def/abcd/gh".matches(pattern));
System.out.println("abcd/xyz/gh".matches(pattern));
prints
true
true
false
false
Using regex is more convenient (?), but please time yourself whether it is faster:
if (!searchString.contains("/")) {
return input.matches("(.*/)?" + Pattern.quote(searchString) + "(/.*)?");
} else {
return false;
}
I made sure that the searchString does not contain /, before inserting it as literal with Pattern.quote. The regex will make sure that there is a / before and after the search string in the input, either that or the search string is the first or last token in the input.
try this regex
s.matches("^abc/.+|.+/abc/.+|.+/abc$")
or
s.startsWith("abc/") || s.contains("/abc/") || s.endsWith("/abc")

Categories

Resources