Objective-C中字符串的拼接方法小结


在 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.phpstudy.net"
//测试服务器
//#define DOMAINXX @"192.168.0.10"


#define API_SYSTEM @"http://"API_DOMAIN@"/system/"
#define API_USER @"http://"API_DOMAIN@"/user/"

 API_SYSTEM 宏展开后是:

@"http://"@"www.phpstudy.net"@"/system/"

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

c语言下的实现:

复制代码 代码如下:

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

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

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



« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3