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...
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.
Example: This is my string,
String sample = "s5656";
If the first character of the string contains 's' or 'p' or 'r' means i should remove the character,Otherwise i have to
return the original string.
Is there any optimized way to do that like "regex" or "StringUtils" in apache common?
Why do you want to add 3rd party jar for this kind of simple requirement? You can try as follows
String sample = "s5656";
if(sample.startsWith("s")||sample.startsWith("r")||sample.startsWith("p")){
// do necessary
}else{
// do necessary
}
String#startsWith()
A simple regex could solve your problem :
public static void main(String[] args) {
String s = "s5656s";
System.out.println(s.replaceFirst("^[spr]", "")); // a String which begins with s,p or r
}
O/P:
5656s
PS: regex here leads to smaller/simpler but inefficient code. Use Ruchira's answer for a rather long but efficient code. :)
^(s|p|r)
Try this.Use yourString.replaceAll() / replaceFirst() with empty string.Use m.
See demo.
http://regex101.com/r/dZ1vT6/49
I should go for replaceAll function with multiline modifier (?m).
String s = "s5656s\n" +
"r878dsjhj\n" +
"fshghg";
System.out.println(s.replaceAll("(?m)^[spr]", ""));
Output:
5656s
878dsjhj
fshghg
I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);
I have a String , from which i need to omit a particular word from it .
As shown below the String may contain a Word "Baci" OR "BACI" in it
I have written a sample program shown below which works fine , but i want to know if there is better way to do it ??
public class Test {
public static void main(String args[]) {
String str = "Mar 14 Baci WIC";
if(str!=null&&!str.isEmpty())
{
if(str.contains("Baci") || str.contains("BACI"))
{
str = str.replaceAll("(?i) Baci", "");
}
}
System.out.println(str);
}
}
I think better way here will be to not additionally check the existance of "Baci", i.e. without the following if check
if(str.contains("Baci") || str.contains("BACI"))
You could improve it a little by using the \b regexp (which matches a "word boundary") :
str = str.replaceAll("(?i) Baci\\b", "");
That way, you code will not replace "my bacil is..." with "myl is..."
Your second if condition is unnecessary, since replaceAll() will replace zero or more occurrences of the String without error.
you can .toUpperCase your String and then only ask for contains("BACI"). Inside the if block, then just call replace twice with both Baci and BACI.
Thinking it again, I think it's better just calling replace twice without asking if your String contains it or not. If it doesn't find anything to replace, then it won't replace nothing.
Hope it would be useful!
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);
}