How to remove spaces from blackberry URL [duplicate] - java
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Blackberry URL encoder
i am using
String url="http://xxxxxx.com/api/api.php?func=xxxxxxxxxxxx¶ms[]="+searchText+CustomUtility.getConnectionString();
HttpConnection conn=(HttpConnection)Connector.open(url);
InputStream in=(InputStream)conn.openInputStream();
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
parser.parse(in, new ContactParser());
problem is this when searchText has many spaces it is not working , so please how i can remove spaces from URL
try this -
URLUTF8Encoder.enceode(searchText);
URLUTF8Encoder class is given below-
public class URLUTF8Encoder {
final static String[] hex = {
"%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
"%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F",
"%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
"%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F",
"%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
"%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F",
"%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
"%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F",
"%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
"%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F",
"%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
"%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F",
"%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
"%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F",
"%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
"%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F",
"%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
"%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F",
"%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
"%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F",
"%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7",
"%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF",
"%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7",
"%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF",
"%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7",
"%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF",
"%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7",
"%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF",
"%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7",
"%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF",
"%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7",
"%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF"
};
public static String encode(String s)
{
StringBuffer sbuf = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') { // 'A'..'Z'
sbuf.append((char)ch);
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z'
sbuf.append((char)ch);
} else if ('0' <= ch && ch <= '9') { // '0'..'9'
sbuf.append((char)ch);
} else if (ch == ' ') { // space
//sbuf.append('+');
sbuf.append("%20");
} else if (ch == '!') {
sbuf.append("%21");
} else if (ch == '*') {
sbuf.append("%2A");
} else if (ch == '(') {
sbuf.append("%28");
} else if (ch == ')') {
sbuf.append("%29");
} else if (ch == '\'') {
sbuf.append("%27");
} else if (ch == '-' || ch == '_' // unreserved
|| ch == '.'
|| ch == '~' || ch == '\'') {
sbuf.append((char)ch);
} else if (ch <= 0x007f) { // other ASCII
sbuf.append(hex[ch]);
} else if (ch <= 0x07FF) { // non-ASCII <= 0x7FF
sbuf.append(hex[0xc0 | (ch >> 6)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
} else { // 0x7FF < ch <= 0xFFFF
sbuf.append(hex[0xe0 | (ch >> 12)]);
sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
}
}
return sbuf.toString();
}
}
you can use the below code to remove white space character in a given string ,you can call this method like this:
replace("PassyourString" , " " , "");
public static String replace(String s, String f, String r) {
if (s == null) {
return s;
}
if (f == null) {
return s;
}
if (r == null) {
r = "";
}
int index01 = s.indexOf(f);
while (index01 != -1) {
s = s.substring(0, index01) + r + s.substring(index01 + f.length());
index01 += r.length();
index01 = s.indexOf(f, index01);
}
return s;
}
Related
How do I unescape a JSON String using Java/Jackson?
I am using Jackson version 2.4.3 for converting my complex Java object into a String object, so below is what I'm getting in output. The output is like below (Fyi - I just printed some part of the output) "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}"; Here is my code (PaymentTnx is a complex Java object) ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); String lpTransactionJSON = mapper.writeValueAsString(paymentTxn); I don't want to see \ slashes in my JSON string. What do I need to do to get a string like below: "{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";
String test = "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}"; System.out.println(StringEscapeUtils.unescapeJava(test)); This might help you.
I have not tried Jackson. I just have similar situation. I used org.apache.commons.text.StringEscapeUtils.unescapeJson but it's not working for malformed JSON format like {\"name\": \"john\"} So, I used this class. Perfectly working fine. https://gist.githubusercontent.com/jjfiv/2ac5c081e088779f49aa/raw/8bda15d27c73047621a94359492a5a9433f497b2/JSONUtil.java // BSD License (http://lemurproject.org/galago-license) package org.lemurproject.galago.utility.json; public class JSONUtil { public static String escape(String input) { StringBuilder output = new StringBuilder(); for(int i=0; i<input.length(); i++) { char ch = input.charAt(i); int chx = (int) ch; // let's not put any nulls in our strings assert(chx != 0); if(ch == '\n') { output.append("\\n"); } else if(ch == '\t') { output.append("\\t"); } else if(ch == '\r') { output.append("\\r"); } else if(ch == '\\') { output.append("\\\\"); } else if(ch == '"') { output.append("\\\""); } else if(ch == '\b') { output.append("\\b"); } else if(ch == '\f') { output.append("\\f"); } else if(chx >= 0x10000) { assert false : "Java stores as u16, so it should never give us a character that's bigger than 2 bytes. It literally can't."; } else if(chx > 127) { output.append(String.format("\\u%04x", chx)); } else { output.append(ch); } } return output.toString(); } public static String unescape(String input) { StringBuilder builder = new StringBuilder(); int i = 0; while (i < input.length()) { char delimiter = input.charAt(i); i++; // consume letter or backslash if(delimiter == '\\' && i < input.length()) { // consume first after backslash char ch = input.charAt(i); i++; if(ch == '\\' || ch == '/' || ch == '"' || ch == '\'') { builder.append(ch); } else if(ch == 'n') builder.append('\n'); else if(ch == 'r') builder.append('\r'); else if(ch == 't') builder.append('\t'); else if(ch == 'b') builder.append('\b'); else if(ch == 'f') builder.append('\f'); else if(ch == 'u') { StringBuilder hex = new StringBuilder(); // expect 4 digits if (i+4 > input.length()) { throw new RuntimeException("Not enough unicode digits! "); } for (char x : input.substring(i, i + 4).toCharArray()) { if(!Character.isLetterOrDigit(x)) { throw new RuntimeException("Bad character in unicode escape."); } hex.append(Character.toLowerCase(x)); } i+=4; // consume those four digits. int code = Integer.parseInt(hex.toString(), 16); builder.append((char) code); } else { throw new RuntimeException("Illegal escape sequence: \\"+ch); } } else { // it's not a backslash, or it's the last character. builder.append(delimiter); } } return builder.toString(); } }
With Jackson do: toString(paymentTxn); with public String toString(Object obj) { try (StringWriter w = new StringWriter();) { new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj); return w.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
This here is not valid JSON: "{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}"; This here is valid JSON, specifically a single string value: "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}"; Given that you're calling writeValueAsString, this is the correct behaviour. I would suggest writeValue, perhaps?
Phone numbers in java
I've got the code to put a seven letter phrase into a phone number. The hyphen is not returning in the correct spot. I really don't know how to fix this problem. It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem! Code: import java.util.*; import java.lang.*; public class Project1 { public static char getNumber(char letter) { char ret = 0; if (letter== 'A' || letter=='a' || letter== 'B' || letter=='b' || letter=='C' || letter=='c') { return '2'; } else if (letter== 'D' || letter=='d' || letter== 'E' || letter=='e' || letter=='F' || letter=='f') { return '3'; } else if (letter== 'G' || letter=='g' || letter== 'H' || letter=='h' || letter=='I' || letter=='i') { return '4'; } else if (letter== 'J' || letter=='j' || letter== 'K' || letter=='k' || letter=='L' || letter=='l') { return '5'; } else if (letter== 'M' || letter=='m' || letter== 'N' || letter=='n' || letter=='O' || letter=='o') { return '6'; } else if (letter== 'P' || letter=='p' || letter== 'Q' || letter=='q' || letter=='R' || letter=='r'|| letter=='S' || letter=='s') { return '7'; } else if (letter== 'T' || letter=='t' || letter== 'U' || letter=='u' || letter=='V' || letter=='v') { return '8'; } else if (letter== 'W' || letter=='w' || letter== 'X' || letter=='x' || letter=='Y' || letter=='y' || letter=='Z' || letter=='z') { return '9'; } if (letter == ' ') return '-'; return ret; } public static void main (String[] arg) { Scanner input = new Scanner(System.in); System.out.println("Please enter a 7 letter phrase: "); String number = input.nextLine(); for (int i = 0; i < 8; i++) { System.out.print(getNumber(number.toUpperCase().charAt(i))); } } }
It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem! Here you go! A bit of regex is always good for the soul: { String number = input.nextLine(); final StringBuilder builder = new StringBuilder(); // Buffer the sequence. for (int i = 0; i < 8; i++) { builder.append(getNumber(number.toUpperCase().charAt(i))); if (builder.toString().getCharAt(2) != '-') // If the format isn't correct, fix it System.out.println(builder.toString().replaceFirst("(...)(.).(...)", "$1-$2$3")) } } As seen from CSáµ 's comment, you can use the following universal regex instead, such that the section becomes: builder.toString().replaceFirst("^\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*$", "$1$2$3-$4$5$6$7"); Edit: Updated regex as \N backreferences does not work in Java.
Here's a quick and dirty solution to your problem. import java.util.*; public class Project1 { public static char getNumber(char letter) { char ret = 0; if( letter < 'A' ) { ret = '0'; } else if( letter < 'D' ) { ret = '2'; } else if( letter < 'G' ) { ret = '3'; } else if( letter < 'J' ) { ret = '4'; } else if( letter < 'M' ) { ret = '5'; } else if( letter < 'P' ) { ret = '6'; } else if( letter < 'T' ) { ret = '7'; } else if( letter < 'W' ) { ret = '8'; } else if( letter <= 'Z' ) { ret = '9'; } else { ret = '0'; } return ret; } public static void main (String[] arg) { Scanner input = new Scanner(System.in); System.out.println( "Please enter a 7 letter phrase: " ); String number = input.nextLine().toUpperCase(); StringBuffer buff = new StringBuffer(); for( int i = 0, j = 0; j < number.length() && i < 7; j++ ) { char c = number.charAt(j); if( c != ' ' ) { if( i == 3 ) { buff.append( '-' ); } buff.append( getNumber( c ) ); i++; } } System.out.println( buff ); } } Key points: There is no need to check for lower case if the alpha characters are guaranteed to be uppercase. There is no need to uppercase the input string on each iteration of the loop. Do it once at the beginning. I'm ignoring spaces, and always adding a hyphen before I print position 3 (ie the fourth character). chars can be compared just like numbers, using ranges. This simplifies the amount of code quite a bit (ie. each letter within a range doesn't need to be written down).
Why am I getting an empty stack exception? [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 8 years ago. Improve this question Please help in this regard, the error is shown as empty stack exception. Code: import java.util.Stack; public class Stacks { public static void main(String[] arg) { String s[] = {"5 + ) * ( 2", // " 2 + ( - 3 * 5 ) ", "(( 2 + 3 ) * 5 ) * 8 ", "5 * 10 + ( 15 - 20 ) ) - 25", " 5 + ( 5 * 10 + ( 15 - 20 ) - 25 ) * 9" }; for (int i = 0; i < s.length; i++) { Arithmetic a = new Arithmetic(s[i]); if (a.isBalance()) { System.out.println("Expression " + s[i] + " is balanced\n"); a.postfixExpression(); System.out.println("The post fixed expression is " + a.getPostfix()); a.evaluateRPN(); } else System.out.println("Expression is not balanced\n"); } } private static class Arithmetic { String str = ""; Stack<Character> stack = new Stack<>(); String postFix = ""; public Arithmetic(String str) { this.str = str; this.postFix = postFix; } private boolean isBalance() { Stack<Character> stack = new Stack<>(); for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == '(' ) stack.push(str.charAt(i)); else if(str.charAt(i) == ')') { if(stack.isEmpty() || stack.pop() != '(') return false; } } return stack.isEmpty(); } private void evaluateRPN() { } private String getPostfix() { return postFix; } #SuppressWarnings("empty-statement") private void postfixExpression() { Stack<Character> stack = new Stack<>(); for(int i = 0; i < str.length(); i++) { if(Character.isDigit(str.charAt(i))) postFix += " " + str.charAt(i); else if(str.charAt(i) == '+' || str.charAt(i) == '-' || str.charAt(i) == '*' || str.charAt(i) == '/' || str.charAt(i) == '%' || str.charAt(i) == '(' || str.charAt(i) == ')' ) { do{ stack.push(str.charAt(i)); } while(stack.isEmpty()); } if(str.charAt(i) == '(' || str.charAt(i) == ')') { if(str.charAt(i) == '(') stack.push(str.charAt(i)); else if(str.charAt(i) == ')') { do { do{ postFix += stack.pop(); }while(stack.pop() != ')'); }while(!stack.empty()); } } if(str.charAt(i) == '+' || str.charAt(i) == '-' || str.charAt(i) == '*' || str.charAt(i) == '/' ) { if(str.charAt(i) == '+' || str.charAt(i) == '-') { do{ postFix += stack.pop(); }while ((stack.pop() != '(') || !stack.empty()); postFix += str.charAt(i); } if(str.charAt(i) == '*' || str.charAt(i) == '/') { if(stack.pop() == '+' || stack.pop() == '-') { stack.push(str.charAt(i)); } } } } do{ postFix += stack.pop(); }while(!stack.empty()); } } }
When you testing use peek function otherwise you are removing the item. When you do : if(stack.pop() == '+' || stack.pop() == '-') and your stack contains [*] When you call stack.pop() you remove * and your stack will be empty after that and you will get exception in second test (stack.pop() == '-'). You need to verify your code and change your logic.
stack implementation issue / not printing certain characters
I'm attempting to write an infix to postfix calculator. I am reading from a file that contains: (4>3)+(3=4)+2 When i run my code, i should be getting a string containing the postfix notation of the input, however i get absolutely nothing. my code doesnt seem to be reaching the final print statement. also when i modidy the code to get it to at least print(although the notation is incorrect) it only prints the numbers and not the operators ( +, -, &, etc). I cannot figure out why this is happening! i labeled in the code below where the print statement is: public static void main(String[] args) { readMathFile(); } static String PF = ""; public static void postfix(char c, myStack s, myQueue q) { if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') { String cc = Character.toString(c); PF.concat(cc); } else if(c == '!' || c == '*' || c == '/' || c == '+' || c == '-' || c == '<' || c == '>' || c == '=' || c == '&' || c == '|') { if(s.isEmpty()) s.push(c); else { char top = s.peek(); while ((precedence(top) > precedence(c)) && !s.isEmpty()) { String cd = Character.toString(s.pop()); PF.concat(cd); } s.push(c); } } } public static myStack s; public static myQueue q; public static int i = 1; // the file reading code was borrowed from: // http://www.java2s.com/Code/Java/File-Input-Output/Readfilecharacterbycharacter.htm public static void readMathFile() { s = new myStack(); q = new myQueue(); File file = new File("test.txt"); if (!file.exists()) { System.out.println(file + " does not exist."); return; } if (!(file.isFile() && file.canRead())) { System.out.println(file.getName() + " cannot be read from."); return; } try { FileInputStream fis = new FileInputStream(file); char current; // in this while loop is where all of the reading happens while (fis.available() > 0) { current = (char) fis.read(); //readMath(current, s, q); postfix(current, s, q); } if(fis.available() == 0) { char x = s.pop(); while(!s.isEmpty()) { //q.enqueue(s.pop()); String ce = Character.toString(s.pop()); PF.concat(ce); } } } catch (IOException e) { e.printStackTrace(); } System.out.println("\n\n"+PF); // <----CODE NEVER REACHES THIS POINT! (and when i modify so it does, it will not print the operators!) }
Reading in text file gives ArrayIndexOutOfBoundsException
I am attempting to read this .txt file into my program (as an improvement over manual input) and i am having trouble converting my methods to accept the input txt file. i get a arrayindexoutofboundsexception on line "infix[--pos]='\0';" class Functions { void postfix(char infix[], char post[]) { int position, und = 1; int outposition = 0; char topsymb = '+'; char symb; Stack opstk = new Stack(); opstk.top = -1; for (position = 0; (symb = infix[position]) != '\0'; position++) { if (isoperand(symb)) post[outposition++] = symb; else { if (opstk.isempty() == 1) und = 1; else { und = 0; topsymb = opstk.pop(); } while (und == 0 && precedence(topsymb, symb) == 1) { post[outposition++] = topsymb; if (opstk.isempty() == 1) und = 1; else { und = 0; topsymb = opstk.pop(); } }// end while if (und == 0) opstk.push(topsymb); if (und == 1 || (symb != ')')) opstk.push(symb); else topsymb = opstk.pop(); }// end else }// end for while (opstk.isempty() == 0) post[outposition++] = opstk.pop(); post[outposition] = '\0'; }// end postfix function int precedence(char topsymb, char symb) { /* check precedence and return 0 or 1 */ if (topsymb == '(') return 0; if (symb == '(') return 0; if (symb == ')') return 1; if (topsymb == '$' && symb == '$') return 0; if (topsymb == '$' && symb != '$') return 1; if (topsymb != '$' && symb == '$') return 0; if ((topsymb == '*' || topsymb == '/') && (symb != '$')) return 1; if ((topsymb == '+' || topsymb == '-') && (symb == '-' || symb == '+')) return 1; if ((topsymb == '+' || topsymb == '-') && (symb == '*' || symb == '/')) return 0; return 1; } /* end precedence function */ private boolean isoperand(char symb) { /* Return 1 if symbol is digit and 0 otherwise */ if (symb >= '0' && symb <= '9') return true; else return false; }/* end isoperand function */ } public class Driver { public static void main(String[] args) throws IOException { Functions f = new Functions(); char infix[] = new char[80]; char post[] = new char[80]; int pos = 0; char c; System.out.println("\nEnter an expression is infix form : "); try { BufferedReader in = new BufferedReader(new FileReader("infix.txt")); String str; while ((str = in.readLine()) != null) { infix = str.toCharArray(); } in.close(); } catch (IOException e) { } infix[--pos] = '\0'; System.out.println("The original infix expression is : "); for (int i = 0; i < pos; i++) System.out.print(infix[i]); f.postfix(infix, post); System.out.println("\nThe postfix expression is : "); for (int i = 0; post[i] != '\0'; i++) System.out.println(post[i]); } }
Do should never ever do like this: try { ... } catch (IOException e) { } You loose some essential information about your code-running. At lease you should print the stack trace to follow the investigation: e.printStackTrace(); You may have a FileNotFound exception. In addition you try to index your array to -1 in infix[--pos], pos is set to 0 before this statement.
1) Totally aside, but I think line in main should read:System.out.println("\nEnter an expression in infix form : "); 2) As well, i agree about the catch statement. You already have narrowed it down to being an IOExcpetion, but you can find so much more info out by printing wither of the following inside the catch System.err.println(e.getMessage()); or e.printStackTrace() Now to answer your question. You are initializing pos to the value 0, but the you are doing a PREINCREMENT on the line infix[--pos] = '\0'; so pos becomes -1 (clearly outside the scope of the array bounddaries). I think you want to change that to a post increment infix[pos--] = '\0';. Perhaps? And yes, your code DOES Look like C...