URLEncoding from Objc to Swift 3 - ios

We are using following URL encoding in Objective C now we are migrating to swift .what will be the equivalent encoding for below ObjC to swift 3.
- (NSString *) URLEncodedString {
NSMutableString * output = [NSMutableString string];
const unsigned char * source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:#"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}

This code should generate exactly the same result as your Objective-C code.
(Should compile and work as expected in both Swift 3 and 4.)
extension String {
var urlEncoded: String {
var output = ""
for thisChar in self.utf8 {
switch thisChar {
case UInt8(ascii: " "):
output.append("+")
case UInt8(ascii: "."), UInt8(ascii: "-"), UInt8(ascii: "_"), UInt8(ascii: "~"),
UInt8(ascii: "a")...UInt8(ascii: "z"),
UInt8(ascii: "A")...UInt8(ascii: "Z"),
UInt8(ascii: "0")...UInt8(ascii: "9"):
output.append(Character(UnicodeScalar(UInt32(thisChar))!))
default:
output = output.appendingFormat("%%%02X", thisChar)
}
}
return output
}
}
print("https://www.google.es".urlEncoded) //->https%3A%2F%2Fwww.google.es
Some points:
You can iterate on each UTF-8 byte with for thisChar in self.utf8
To convert a string literal (actually a UnicodeScalar Literal) to a UInt8, you can use UInt8(ascii:)
You should better consider using addingPercentEncoding(withAllowedCharacters:) with proper CharacterSet and pre/post-processing

You can probably do it this way -
extension String{
func urlEncodedString() -> String {
var output = String()
let source: [UInt8] = Array(self.utf8)
let sourceLen: Int = source.count
for i in 0..<sourceLen {
let thisChar = source[i]
if thisChar == UInt8(ascii: " ") {
output += "+"
}
else if thisChar == UInt8(ascii: ".") || thisChar == UInt8(ascii: "-") || thisChar == UInt8(ascii: "_") || thisChar == UInt8(ascii: "~") || (thisChar >= UInt8(ascii: "a") && thisChar <= UInt8(ascii: "z")) || (thisChar >= UInt8(ascii: "A") && thisChar <= UInt8(ascii: "Z")) || (thisChar >= UInt8(ascii: "0") && thisChar <= UInt8(ascii: "9")) {
output += "\(Character(UnicodeScalar(UInt32(thisChar))!))"
}
else {
output += String(format: "%%%02X", thisChar)
}
}
return output
}
}

Just replace below code (Swift 3.1.1):
func urlEncodedString() -> String {
var output = String()
let source: [UInt8] = UInt8(utf8)
let sourceLen: Int = strlen(CChar(source))
for i in 0..<sourceLen {
let thisChar: UInt8 = source[i]
if thisChar == " " {
output += "+"
}
else if thisChar == "." || thisChar == "-" || thisChar == "_" || thisChar == "~" || (thisChar >= "a" && thisChar <= "z") || (thisChar >= "A" && thisChar <= "Z") || (thisChar >= "0" && thisChar <= "9") {
output += "\(thisChar)"
}
else {
output += String(format: "%%%02X", thisChar)
}
}
return output
}

Try this swift 3 compatible code. I've tested it in a playground and works fine.
extension String {
func urlEncodedString() -> String {
var output = ""
for thisChar in self.utf8 {
if thisChar == UInt8(ascii: " ") {
output += "+"
}
else if thisChar == UInt8(ascii: ".") ||
thisChar == UInt8(ascii: "-") ||
thisChar == UInt8(ascii: "_") ||
thisChar == UInt8(ascii: "~") ||
(thisChar >= UInt8(ascii: "a") && thisChar <= UInt8(ascii: "z")) ||
(thisChar >= UInt8(ascii: "A") && thisChar <= UInt8(ascii: "Z")) ||
(thisChar >= UInt8(ascii: "0") && thisChar <= UInt8(ascii: "9")) {
output += "\(Character(UnicodeScalar(UInt32(thisChar))!))"
}
else {
output += String(format: "%%%02X", thisChar)
}
}
return output
}
}
Example usage:
let url = "https://www.google.es".urlEncodedString()
print(url)

Related

String Task Codeforces Problem - https://codeforces.com/problemset/problem/118/A

https://codeforces.com/problemset/problem/118/A
my code:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string str;
cin >> str;
for(int i=0; i<sizeof(str); i++)
{
if(str[i] >= 'A' && str[i] <= 'Z')
str[i]+=32;
{
if(str[i] >= 'a' && str[i] <= 'z' && str[i] != 'a' && str[i] != 'e' && str[i] != 'i' && str[i] != 'o' && str[i] != 'u' && str[i] != 'A' && str[i] != 'E' && str[i] != 'I' && str[i] != 'O' && str[i] != 'U')
cout << "." << str[i];
}
}
return 0;
}
Where is the problem in this code because it gives wrong when I submit?
I am not seeing any problem, could anyone help me to detect?
In the question they have included 'y' as a vowel too. I changed some other stuff too (like, use i<str.size() not i<sizeof(str) ), try the following code it will get accepted :
int main()
{
string str;
cin >> str;
for(int i=0; i<str.size(); i++)
{
char temp;
temp = str[i];
if(temp >= 'A' && temp <= 'Z')
temp = tolower(temp);
if(temp != 'a' && temp != 'e' && temp != 'i' && temp != 'o' && temp != 'u' && temp != 'y')
cout << "." << temp;
}
return 0;
}

MQL4 my first EA overtrades if I increase the amount of conditions it calculates

I have created an expert advisor that calculates some conditions and gives a value either long or short for each condition (+or- 0.1 lots), it then sums all the conditions to give a net long or short position.
It should then either open a new order or close an open one to alter the previous open positions(mlots) to match the target value the trade conditions have calculated(sum) on the change of each new bar; this is done by using the ontick function.
If I use only one or two conditions it works fine, but when I increase the number of conditions (sum can be greater than 0.2 lots or less than -0.2lots) it over trades by one and then closes the position which it should and then over trades by one again which it shouldn't get in to a nasty cycle.
I don't understand why it would work perfectly for two conditions but not for more than two I wonder if anyone has an idea I would be grateful for any input.
This is my first attempt at an EA any thoughts would be greatly appreciated best regards Ken
//+------------------------------------------------------------------+
//| test.mq4 |
//| Copyright 2018, K T |
//| https:// |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, K T"
#property link ""
#property version "1.00"
#property strict
#property description "SIMPLE TRADER"
//INPUT PARAMETERS
input double lots=0.1;
input int MagicNumber=1111;//MAGICNO MUST BE UNIQUE
input int condno=1; //1=3/10 10 2=10 10/20 3=ALL
input double test=0.0;
input int spread=1;
input int slippage=10;
input string simble="FTSE100(£)";
input int period=PERIOD_M1;
input double TP=200;
input double SL=100;
input int ma1input=3;
input int ma2input=10;
input int ma3input=20;
input int sleep=0;
//ONINIT TEST FOR CORRECR CONDITIONS
int OnInit()
{
string simble1=simble;
int period1=period;
if (simble1==Symbol()&& period1==Period() && Ask-Bid<=spread)
{
Alert ("CORRECT SYMBOL ", simble," mlots=", mlots(),"sum= ",sum());
Alert ("CORRECT TIME T", period);
return(INIT_SUCCEEDED);
}
else
{
Alert ("INIT FAILED");
Alert ("wrong symbol, time or spread too wide");
return(INIT_FAILED);
}
}
//ON EVERY TICK
void OnTick()
{
double sum1 = sum();
double mlots1 = mlots();
if(sum1 == mlots1)
{
neutral();
return;
}
else if(sum1>mlots1 && mlots1>=0 && mlots1!= sum1)
{
openbuy();
return;
}
else if(sum1>mlots1 && mlots1<0 && mlots1!= sum1)
{
closesell();
return;
}
else if(sum1<mlots1 && mlots1<=0 && mlots1!= sum1)
{
opensell();
return;
}
else if(sum1<mlots1 && mlots1>0 && mlots1!= sum1)
{
closebuy();
return;
}
else
return;
}
//NEUTRAL
void neutral()
{
Alert("T", period, " EQUILIBRIUM ", simble,"/ sum=",sum(),"/ mlots=" ,mlots());
return;
}
//OPEN BUY
void openbuy()
{
double TakeProfitLevel;
double StopLossLevel;
TakeProfitLevel = Bid + TP*Point*10; //0.00001 * 10 = 0.0001
StopLossLevel = Bid - SL*Point*10;
if(mlots()!= sum())
{
OrderSend(simble, OP_BUY, lots, Ask, slippage*10, StopLossLevel, TakeProfitLevel, "BUY", MagicNumber);//notice that slippage also has to be multiplied by 10
Alert(MagicNumber," T", period, " OPENBUYFCTION = ", simble,"/ sum=",sum(),"/ mlots=" ,mlots());
Sleep(sleep);
return;
}
else
{
return;
}
}
//OPEN SELL
void opensell()
{
double TakeProfitLevel;
double StopLossLevel;
//here we are assuming that the TakeProfit and StopLoss are entered in Pips
TakeProfitLevel = Ask - TP*Point*10; //0.00001 * 10 = 0.0001
StopLossLevel = Ask + SL*Point*10;
if (mlots()!= sum())
{
OrderSend(simble, OP_SELL, lots, Bid, slippage*10, StopLossLevel, TakeProfitLevel, "SELL", MagicNumber); //notice that slippage also has to be multiplied by 10
Alert(MagicNumber," T", period, " OPENSELLFCTION = ", simble,"/ sum=",sum(),"/ mlots=" ,mlots());
Sleep(sleep);
return;
}
else
{
return;
}
}
//CLOSE BUY
void closebuy()
{
if(mlots()==sum())
{
neutral();
return;
}
int low=OrderTicket();
int i=OrdersTotal();
for (i = OrdersTotal(); i >=0; i--)
{
if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) continue;
if (i<=OrdersTotal() && OrderType()== OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber )
bool closed = OrderClose( low, OrderLots(), Bid, slippage, White);
Alert("Ticket= ", low);
Alert(MagicNumber," T", period, " CLOSEBUYFCTION = ", simble,"/ sum=",sum(),"/ mlots=" ,mlots());
Sleep(sleep);
return;
}
}
//CLOSE SELL
void closesell()
{
if(mlots()==sum())neutral();
int low=OrderTicket();
int i=OrdersTotal();
for (i = OrdersTotal(); i >=0; i--)
{
if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) continue;
if (i<=OrdersTotal() && OrderType()== OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber )
bool closed = OrderClose( low, OrderLots(), Ask, slippage, White);
Alert("Ticket= ", low);
Alert(MagicNumber," T", period, " CLOSESELLFCTION = ", simble,"/ sum=",sum(),"/ mlots=" ,mlots());
Sleep(sleep);
return;
}
}
//CONDITION 1
double cond1() //cond 1 3ema 10ma
{
double ma1;
double ma2;
ma1=iMA(NULL,0,ma1input,0,MODE_EMA,PRICE_CLOSE,1);//3EMA
ma2=iMA(NULL,0,ma2input,0,MODE_SMA,PRICE_CLOSE,1);//10MA
if(ma1>=ma2)
{
return(lots);
}
else
{
return(lots*-1);
}
}
//CONDITION 2
double cond2() //cond 2 10ema 10ma
{
double ma1;
double ma2;
ma1=iMA(NULL,0,ma1input,0,MODE_EMA,PRICE_CLOSE,1);//3EMA
ma2=iMA(NULL,0,ma2input,0,MODE_EMA,PRICE_CLOSE,1);//10EMA
if(ma1>=ma2)
{
return(lots);
}
else
{
return(lots*-1);
}
}
//CONDITION 3
double cond3() //cond 3 10ema 20ema
{
double ma1;
double ma2;
ma1=iMA(NULL,0,ma2input,0,MODE_EMA,PRICE_CLOSE,1);//10EMA
ma2=iMA(NULL,0,ma3input,0,MODE_EMA,PRICE_CLOSE,1);//20EMA
if(ma1>=ma2)
{
return(lots);
}
else
{
return(lots*-1);
}
}
//CONDITION 4
double cond4() //cond 4 10ma 20Ema
{
double ma1;
double ma2;
ma1=iMA(NULL,0,ma2input,0,MODE_SMA,PRICE_CLOSE,1);//10MA
ma2=iMA(NULL,0,ma3input,0,MODE_EMA,PRICE_CLOSE,1);//20EMA
if(ma1>=ma2)
{
return(lots);
}
else
{
return(lots*-1);
}
}
//SELECTING CONDITIONS TO BE INCLUDED
double sum()
{
if(condno==1)
{
return(cond1() + cond2());
}
else if(condno==2)
{
return(cond3() + cond4());
}
else if (condno==3)
{
return(cond1() + cond2()+ cond3() + cond4() );//IF MORE THAN TWO CONDITIONS USED IT OVERTRADES B ONE AND THEN CLOSES ERROR TRADE
}
else
return(cond1() + cond2());
}
//COUNT OF ALL OPEN TRADES
double mlots()
{
double mlots1 = BuyTotalMagicOpen() + SellTotalMagicOpen();
double mlots2 = mlots1/10;
return (mlots2);
}
//COUNT BUY ORDERS
double BuyTotalMagicOpen()
{
int OrderCount = 0;
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) continue;
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
if (OrderType() == OP_BUY) OrderCount++;
}
return (OrderCount);
}
//COUNT SELL ORDERS
double SellTotalMagicOpen()
{
int OrderCount = 0;
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) continue;
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
if (OrderType() == OP_SELL) OrderCount++;
}
return (OrderCount*-1);
}
//CLOSE ALL MAGICNUMBER REFRESHRATES BUSYSLEEP MODE
void CloseThis() {
for (int i = OrdersTotal(); i >=0; i--) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
while(IsTradeContextBusy()) Sleep(100);
RefreshRates();
if (OrderType() == OP_BUY && Symbol() == OrderSymbol()
&& MagicNumber == OrderMagicNumber()) {
bool closed = OrderClose( OrderTicket(), OrderLots(), Bid, slippage, Red);
Alert("T", period, " BUY CLOSED ON DEINIT");
}
if (OrderType() == OP_SELL && Symbol() == OrderSymbol()
&& MagicNumber == OrderMagicNumber()) {
bool closed = OrderClose( OrderTicket(), OrderLots(), Ask, slippage, Green);
Alert("T", period, " SELL CLOSED ON DEINIT");
}
}
}
//DEINIT
void OnDeinit(const int reason)//MAGIC NO
{
CloseThis();
Alert("T", period, " DEINIT SUCCEEDED");
}
//

What's wrong with this C++ code lottery guessing game?

I am making a simple lottery game application, where three random numbers between 0 and 10 are generated, if the user gets all three in the right order, they get 1 million. If they get one right then they win 10 dollars, and if they get all three but not in order, they win a thousand, if two are matching then they get $1,000. and if they get none right then they get nothing.
Here's my code here.
int main()
{
cout << "Hello, this is the lottery! Three random numbers between 0 and 10 will be generated. Guess what they are and the order!" << endl;
char answer;
cout << "Do you want to play? (y or n): " << endl;
cin >> answer;
while (answer == 'y' || 'Y')
{
srand((unsigned)time(NULL));
int ran1 = rand() % 10;
int ran2 = rand() % 10;
int ran3 = rand() % 10;
int guess1, guess2, guess3;
cout << "Enter your first number guess: " << endl;
cin >> guess1;
cout << "Enter your second number guess: " << endl;
cin >> guess2;
cout << "Enter your third number guess: " << endl;
cin >> guess3;
if ((guess1 != ran1 || ran2 || ran3) && (guess2 != ran1 || ran2 || ran3) && (guess3 != ran1 || ran2 || ran3))
cout << "You won no money. Sucks for you." << endl;
else
if ((guess1 == ran1 || ran2 || ran3) || (guess2 == ran1 || ran2 || ran3) || (guess3 == ran1 || ran2) || ran3)
cout << "You won 10 dollars!" << endl;
else
if ((guess1 && guess2 == ran1 && ran2) || (guess1 && guess3 == ran1 && ran3) || (guess2 && guess3 == ran2 && ran3))
cout << "You won 100 dollars!" << endl;
else
if ((guess1 == ran1 || ran2 || ran3) && (guess2 == ran1 || ran2 || ran3) && (guess3 == ran1 || ran2 || ran3))
cout << "You won 1 thousand dollars! good job!" << endl;
else
if ((guess1 == ran1) && (guess2 == ran2) && (guess3 == ran3))
cout << "You won 1 million dollars! jackpot!" << endl;
cout << "The numbers were " << ran1 << "," << ran2 << "," << ran3 << endl;
cout << "Play again?(y or n): " << endl;
cin >> answer;
if (answer == 'y')
continue;
else
break;
}
cout << "Game Over" << endl;
system("pause");
return 0;
}
when i run this code, things don't go right with the decisions. All it says is "You won no money. sucks for you". Idk what's wrong maybe its something simple but can someone help? Thanks.
if ((guess1 != ran1 || ran2 || ran3) && (guess2 != ran1 || ran2 || ran3) && (guess3 != ran1 || ran2 || ran3))
should be
if ((guess1 != ran1 || guess1 != ran2 || guess1 != ran3) && (guess2 != ran1 || guess2 != ran2 || guess2 != ran3) && (guess3 != ran1 || guess3 != ran2 || guess3 != ran3))
It is not the order of the conditionals, even though there are flaws there as well, but is the way in which you have written the conditionals.
(guess1 == ran1 || ran2) is different than (guess1 == ran1 || guess1 == ran2)
This is because in c++ a number other than 0 evaluates to true. This is why it is evaluating to true every time.
For example, say guess1 = 1, ran1 = 2, and ran2 = 3, then
(guess1 == ran1 || guess1 == ran2) will evaluate to false, but
(guess1 == ran1 || ran2) will evaluate to true.

Objective C URL with Vertical pipes/bars

I am trying to have vertical pipes in the URL
Input String: http://testURL.com/Control?command=dispatch|HOME|ABC:User Name
-(NSString *)getURLEncodedString:(NSString *)stringvalue{
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[stringvalue UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ':' || thisChar == '/' || thisChar == '?' || thisChar == '=' || thisChar == '|' || thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}
Output String after calling above method: http://testURL.com/Control?command=dispatch|HOME|ABC:User%20Name
Now, if I pass the above encode string to [[NSURL URLWithString:encodedString];
I am getting Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xae9d760 {NSUnderlyingError=0xaec8ed0 "bad URL", NSLocalizedDescription=bad URL}
Any input on this guys? I want the URL to look like the encodedString.
Thank you!
I really cannot see a reason to encode/escape your string manually... Any way, this will work just fine:
NSString *urlString = #"http://testURL.com/Control?command=dispatch|HOME|ABC:User Name";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Which outputs:
http://testURL.com/Control?command=dispatch%7CHOME%7CABC:User%20Name
It seems that NSURL doesn't like vertical bars after all, which you didn't encode in your method and thus getting a bad URL code.

Url contain special charectors

I am trying to establish a https connection but my URL contains some special characters, so creating the connection is throwing an Exception. How do I avoid this problem?
You can encode like this,
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('+');
} else if (ch == '-' || ch == '_' // unreserved
|| ch == '.' || ch == '!'
|| ch == '~' || ch == '*'
|| 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();
}
}
referenced By
HTTP://WWW.W3.ORG/INTERNATIONAL/URLUTF8ENCODER.JAVA
There are several solutions for this. Pick the one you like most.

Resources