2010-11-17 155 views
0

我有一個字符串 NSString * const kAUrl = @「http://www.google/start.php?show=best&usr=(here)&pwd=x」;將字符串傳遞給URL。

我想通過另一個字符串 的NSString * A = @ 「AA」;

上面的網址在我寫在這裏(在這裏)在上面的網址。

我怎麼能通過它?

關於。

+0

你爲什麼要創建一個字符串常量,然後嘗試修改? – MystikSpiral 2010-11-17 13:17:00

+0

當它已經是不可變的時,我看不到NSString常量的值。 – 2010-11-17 13:26:27

回答

3

您需要使用 NSString實例方法-[stringByAddingPercentEscapesUsingEncoding:]對適合URL的字符串進行編碼。

然後使用-[stringWithFormat:]放置到URL中。

例如:

-(NSURL*)showBestURLWithUser:(NSString*)user { 
{ 
    user = [user stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 
    static NSString* template = @"http://www.google/start.php?show=best&usr=%@&pwd=x"; 
    NSString* urlString = [NSString stringWithFormat:template, user]; 
    return [NSURL URLWithString:urlString]; 
} 
+0

我想把kAUrl當作const.NOw建議我plz。感謝 – iscavengers 2010-11-17 13:20:07

+0

是否有使用const的原因?該字符串在這種狀態下是不可改變的(因爲它不是一個NSMutableString)... – 2010-11-17 13:23:57

+0

據我所知,const NSString *對象將無法重新分配新的NSString,並且只會使用一個常量字符串(即@「string」)。 – 2010-11-17 13:30:28

3

使用NSString stringWithFormat:

NSString *a = @"hello"; 
NSString *kAUrl = [NSString stringWithFormat:@"http://www.google/start.php?show=best&usr=%@&pwd=x", a]; 

kAUrl現在包含的其中%@是內容。


當心雖然 - 如果a包含任何URL保留字符(即一個&等),它可能會破壞您的網址。

+0

它不會工作,因爲NSString * const a; a是const ..給我error.plz建議。 – iscavengers 2010-11-17 13:11:35

+0

爲什麼它必須是一個常量?只是不要讓它成爲一個常量,你應該沒問題。 – deanWombourne 2010-11-23 16:15:55

1

你將你的宣言改成這樣:

NSString *kAUrl = [NSString stringWithFormat:@"http://www.google/start.php?show=best&usr=%@&pwd=x", a]; 

祝您好運!

1

的NSString * A = @ 「AA」;

的NSString * kAUrl = [NSString的stringWithFormat:@ 「http://www.google/start.php?show=best & USR =%@ & PWD = X」,一個];

kAUrl = [kAUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

工作完成。

+0

不會將整個字符串編碼爲URL嗎?包括URL協議等部分? – 2010-11-17 13:27:57

+0

right.it will。我不能將字符串傳遞給const。 – iscavengers 2010-11-17 13:43:37

+0

你爲什麼需要「const」? – Bourne 2010-11-17 13:58:59