I need to have access to java source files and I am using the String's method trim() to remove any leading and trailing whitespaces. However the code which is some scope, for example:
if(name.equals("joe")){
System.out.println(name);
}
the white spaces for the printing statement are not being removed completely. Is there a way to be able to remove also these white-spaces please?
Thanks
EDIT: I did use a new variable:
String n = statements.get(i).toString().trim();
System.out.println(n);
however the output still looks like this:
System.out.println("NAME:" + m.getName());
BlockStmt bs = m.getBody();
List<Statement> statements = bs.getStmts();
for (int i = 0; i < statements.size(); i++) {
if ((statements.get(i).toString().trim().contains(needed)) & (statements.get(i).toString().trim().length() == needed.length())) {
System.out.println("HEREEEEEEEEEEEEEEEEEEEEEEEEEE");
}
}
Some of the strings are still containing the spaces beforehand
You are mistaken. The String.trim() method does remove leading and trailing whiteshape entirely.
However, I suspect that your real problem is that you don't know what this really means. Java strings are immutable, so trim() obviously doesn't modify the target String object. Instead, it returns a new String instance with the whitespace removed. So you need to use it as follows:
String trimmed = someString.trim();
You must have to assign the result of string. (String objects are immutable).
name=name.trim();
if(name.equals("joe")){
System.out.println(name);
}
As #home mentioned:
if(name.equals("joe")){
String newName = name.trim();
System.out.println(newName);
}
Should work
EDIT: I guess that you want to use trim before the condition. My mistake.
String newName = name.trim();
if(newName.equals("joe")){
System.out.println(newName);
}
Related
I want to be able to trim one quote from each side of a java string. Here are some examples.
"foo" -> foo
"foo\"" -> foo\"
"\"foo\"" -> \"foo\"
I'm currently using StringUtils.trim from common lang but when I end the string with a escaped quote, it trims that too because they are consecutive. I want to be able to trim exactly one quote.
I ended up using org.apache.commons.lang3.StringUtils.substringBetween and it works.
You may also use the substring() method and trim the first and last characters on condition although it's a bit long.
trimedString= s.substring((s.charAt(0)=='"')?1:0 , (s.charAt(s.length()-1)=='"')?s.length()-1:s.length());
I prefer to use this String method
public String[] split(String regex)
basically if you feed in the quotation mark then you will get an array of strings holding all of the chunks between your quotation marks.
String[] parts = originalString.split("\"");
String quoteReduced = parts[0];
for (int i = 1; i < (parts.length() -1); i++){
quoteReduced = quoteReduced.concat( parts[i] +"\"" );
}
quoteReduced = quoteReduced.concat( "\"" +parts[parts.length()-1]);
While it may not be the most straight forward it is the way that I would get around this. The first piece and last piece could be included in the loop but would require an if statement.
I have few Java Strings like below:
ab-android-regression-4.4-git
ab-ios-regression-4.4-git
ab-tablet-regression-4.4-git
However, I do not want such lengthy and unwanted names and so I want to get rid of starting ab- and ending -git part. The pattern for all the Strings is the same (starts with ab and ends with git)
Is there a function/class in Java that will help me in trimming such things? For example, something like:
String test = "ab-android-regression-4.4-git";
test.trim(ab, git)
Also, can StringUtils class help me with this? Thoughts on regular expressions?
EDITED PART: I also want to know how to eliminate the - characters in the Strings and change everything to uppercase letters
Here's a method that's more general purpose to remove a prefix and suffix from a string:
public static String trim (String str, String prefix, String suffix)
{
int indexOfLast = str.lastIndexOf(suffix);
// Note: you will want to do some error checking here
// in case the suffix does not occur in the passed in String
str = str.substring(0, indexOfLast);
return str.replaceFirst(prefix, "");
}
Usage:
String test = "ab-android-regression-4.4-git";
String trim = trim(test, "ab-", "-git"));
To remove the "-" and make uppercase, then just do:
trim = trim.replaceAll("-", " ").toUpperCase();
You can use test = test.replace("ab-", "") and similar for the "-git" or you can use test = StringUtils.removeStart(test, "ab-") and similarly, removeEnd.
I prefer the latter if you can use StringUtils because it won't ever accidentally remove the middle of the filename if those expressions are matched.
Since the parts to trim are constant in size, you should simply use substring :
yourString.substring(3, yourString.length - 4)
If your string always contains ab- at the begining and -git at the end then here is the code
String test = "ab-android-regression-4.4-git";
test=test.substring(3, s.length() - 4);
System.out.println("s is"+s); //output is android-regression-4.4
To know more about substrings click https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html
I've used the following regex to try to remove parentheses and everything within them in a string called name.
name.replaceAll("\\(.*\\)", "");
For some reason, this is leaving name unchanged. What am I doing wrong?
Strings are immutable. You have to do this:
name = name.replaceAll("\\(.*\\)", "");
Edit: Also, since the .* is greedy, it will kill as much as it can. So "(abc)something(def)" will be turned into "".
As mentionend by by Jelvis, ".*" selects everything and converts "(ab) ok (cd)" to ""
The version below works in these cases "(ab) ok (cd)" -> "ok", by selecting everything except the closing parenthesis and removing the whitespaces.
test = test.replaceAll("\\s*\\([^\\)]*\\)\\s*", " ");
String.replaceAll() doesn't edit the original string, but returns the new one. So you need to do:
name = name.replaceAll("\\(.*\\)", "");
If you read the Javadoc for String.replaceAll(), you'll notice that it specifies that the resulting string is the return value.
More generally, Strings are immutable in Java; they never change value.
I'm using this function:
public static String remove_parenthesis(String input_string, String parenthesis_symbol){
// removing parenthesis and everything inside them, works for (),[] and {}
if(parenthesis_symbol.contains("[]")){
return input_string.replaceAll("\\s*\\[[^\\]]*\\]\\s*", " ");
}else if(parenthesis_symbol.contains("{}")){
return input_string.replaceAll("\\s*\\{[^\\}]*\\}\\s*", " ");
}else{
return input_string.replaceAll("\\s*\\([^\\)]*\\)\\s*", " ");
}
}
You can call it like this:
remove_parenthesis(g, "[]");
remove_parenthesis(g, "{}");
remove_parenthesis(g, "()");
To get around the .* removing everything in between two sets of parentheses you can try :
name = name.replaceAll("\\(?.*?\\)", "");
In Kotlin we must use toRegex.
val newName = name.replace("\\(?.*?\\)".toRegex(), "");
I am getting response for some images in json format within this tag:
"xmlImageIds":"57948916||57948917||57948918||57948919||57948920||57948921||57948 922||57948923||57948924||57948925||57948926||5794892"
What i want to do is to separate each image id using .split("||") of the string class. Then append url with this image id and display it.
I have tried .replace("\"|\"|","\"|"); but its not working for me. Please help.
EDIT: Shabbir, I tried to update your question according to your comments below. Please edit it again, if I didn't get it right.
Use
.replace("||", "|");
| is no special char.
However, if you are using split() or replaceAll instead of replace(), beware that you need to escape the pipe symbol as \\|, because these methods take a regex as parameter.
For example:
public static void main(String[] args) {
String in = "\"xmlImageIds\":\"57948916||57948917||57948918||57948919||57948920||57948921||57948922||57948923||57948924||57948925||57948926||5794892\"".replace("||", "|");
String[] q = in.split("\"");
String[] ids = q[3].split("\\|");
for (String id : ids) {
System.out.println("http://test/" + id);
}
}
I think I know what your problem is. You need to assign the result of replace(), not just call it.
String s = "foo||bar||baz";
s = s.replace("||", "|");
System.out.println(s);
I tested it, and just calling s.replace("||", "|"); doesn't seem to modify the string; you have to assign that result back to s.
Edit: The Java 6 spec says "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar." (the emphasis is mine).
According to http://docs.oracle.com/javase/6/docs/api/java/lang/String.html, replace() takes chars instead of Strings. Perhaps you should try replaceAll(String, String) instead? Either that, or try changing your String ("") quotation marks into char ('') quotation marks.
Edit: I just noticed the overload for replace() that takes a CharSequence. I'd still give replaceAll() a try though.
String pipe="pipes||";
System.out.println("Old Pipe:::"+pipe);
System.out.println("Updated Pipe:::"+pipe.replace("||", "|"));
i dont remember how it works that method... but you can make your own:
String withTwoPipes = "helloTwo||pipes";
for(int i=0; i<withTwoPipes.lenght;i++){
char a = withTwoPipes.charAt(i);
if(a=='|' && i<withTwoPipes.lenght+1){
char b = withTwoPipes.charAt(i+1);
if(b=='|' && i<withTwoPipes.lenght){
withTwoPipes.charAt(i)='';
withTwoPipes.charAt(i+1)='|';
}
}
}
I think that some code like this should work... its not a perfect answer but can help...
I want to match on a regex and modify the match. here is my function. right now, my method doesn't change the input at all. what is wrong? thanks.
Matcher abbrev_matcher = abbrev_p.matcher(buffer);
StringBuffer result = new StringBuffer();//must use stringbuffer here!
while (abbrev_matcher.find()){
//System.out.println("match found");
abbrev_matcher.appendReplacement(result, getReplacement(abbrev_matcher));
}
abbrev_matcher.appendTail(result);
private static String getReplacement(Matcher aMatcher){
StringBuilder temp = new StringBuilder(aMatcher.group(0));
for (int i = 0; i < temp.length(); i++){
if (temp.charAt(i) == '.'){
temp.deleteCharAt(i);
}
}
return temp.toString();
}
You just want to remove all the dots from the matched text? Here:
StringBuffer result = new StringBuffer();
while (abbrev_matcher.find()) {
abbrev_matcher.appendReplacement(result, "");
result.append(abbrev_matcher.group().replaceAll("\\.", ""));
}
abbrev_matcher.appendTail(result);
The reason for the appendReplacement(result, "") is because appendReplacement looks for $1, $2, etc., so it can replace them with capture groups. If you aren't passing string literals or other string constants to that method, it's best to avoid that processing step and use StringBuffer's append method instead. Otherwise it will tend to blow up if there are any dollar signs or backslashes in the replacement string.
As for your getReplacement method, in my tests it does change the matched string, but it doesn't do it correctly. For example, if the string is ...blah..., it returns .blah.. That's because, every time you call deletecharAt(i) on the StringBuilder, you change the indexes of all subsequent characters. You would have to iterate through the string backward to make that approach work, but it's not worth it; just start with an empty StringBuilder and build the string by append-ing instead of deleting. It's much more efficient as well as easier to manage.
Now that I think about it some more, the reason you aren't seeing any change may be that your code is throwing a StringIndexOutOfBoundsException, which you aren't seeing because the code runs in a try block and the corresponding catch block is empty (the classic Empty Catch Block anti-pattern). N'est-ce pas?