IOS Objective-c 字符串的拼接方法小结

2017 年 1 月 3 日 0 条评论 2.13k 次阅读 0 人点赞

这篇文章主要介绍了Objective-C中字符串的拼接方法小结,除了依靠NSString,文中还介绍了在宏里拼接字符串的方法,需要的朋友可以参考下

在 java 和 c# 中,字符串的拼接是直接用 + 来操作的。在 OC 中,说是有下面3种方法,
NSString* string; // 结果字符串
NSString* string1, string2; //已存在的字符串,需要将string1和string2连接起来

 

方法1:

string = [NSString initWithFormat:@"%@,%@", string1, string2 ];

方法2:

string = [string1 stringByAppendingString:string2];

方法3:

string = [string stringByAppendingFormat:@"%@,%@",string1, string2];

网上的说法是第二种方法效率更好一点,不过我就感觉不出来什么,具体情况具体对待好了。

在宏里拼接字符串:

 

//正式服务器
#define API_DOMAIN @"www.xxx.com"
//测试服务器
//#define DOMAINXX @"192.168.0.10"</strong>
#define API_SYSTEM @"http://"API_DOMAIN@"/system/"
#define API_USER @"http://"API_DOMAIN@"/user/"

API_SYSTEM 宏展开后是:

@"http://"@"www.xxx.com"@"/system/"

编译器会自动将字符中连接起来,目的实现。

 

c语言下的实现:

//正式服务器
#define API_DOMAIN "www.xxx.com"
//测试服务器
//#define DOMAINXX "192.168.0.10"

#define API_SYSTEM "http://"API_DOMAIN"/system/"

#define API_USER "http://"API_DOMAIN"/user/"

雷雷

这个人太懒什么东西都没留下

文章评论(0)

(Spamcheck Enabled)