1.判断字符串是否为空
if ([text lenght] ==
0) {
// empty string
}
// empty string
}
2.字符串连接
NSString *str1 =
@"
str1
";
NSString *str2 = @" str2 ";
NSString *result;
// 方法1
result = [str1 stringByAppendingString:str2];
NSLog(result, nil);
// 方法2
result = [NSString stringWithFormat: @" %@%@ ", str1, str2];
NSLog(result, nil);
// 方法3
result = [ @"" stringByAppendingFormat: @" %@%@ ", str1, str2];
NSLog(result, nil);
// 方法4
NSMutableString *ms = [[NSMutableString alloc] init];
[ms appendString:str1];
[ms appendString:str2];
NSLog(ms, nil);
[ms release];
// 结果都是:str1str2
NSString *str2 = @" str2 ";
NSString *result;
// 方法1
result = [str1 stringByAppendingString:str2];
NSLog(result, nil);
// 方法2
result = [NSString stringWithFormat: @" %@%@ ", str1, str2];
NSLog(result, nil);
// 方法3
result = [ @"" stringByAppendingFormat: @" %@%@ ", str1, str2];
NSLog(result, nil);
// 方法4
NSMutableString *ms = [[NSMutableString alloc] init];
[ms appendString:str1];
[ms appendString:str2];
NSLog(ms, nil);
[ms release];
// 结果都是:str1str2
一般推荐使用方法1,如果需要大量字符串连接推荐使用方法4,需要更少的内存开销。
3.去除字符串首尾的空格和换行符
NSString *text = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
4.多行书写字符串常量
NSString *str1 =
@"
SELECT [CustomerID], [CustomerName]
"
" FROM [Customer] "
" WHERE [CustomerID] = 1234 ";
NSString *str2 = @" SELECT [CustomerID], [CustomerName] \
FROM [Customer] \
WHERE [CustomerID] = 1234 ";
NSLog(str1, nil);
NSLog(str2, nil);
// 结果都是:SELECT [CustomerID], [CustomerName] FROM [Customer] WHERE [CustomerID] = 1234
" FROM [Customer] "
" WHERE [CustomerID] = 1234 ";
NSString *str2 = @" SELECT [CustomerID], [CustomerName] \
FROM [Customer] \
WHERE [CustomerID] = 1234 ";
NSLog(str1, nil);
NSLog(str2, nil);
// 结果都是:SELECT [CustomerID], [CustomerName] FROM [Customer] WHERE [CustomerID] = 1234
注意字符串中每行结尾处的空格。这种字符串声明方式虽然看上去是多行,实际上字符串中并没有换行符,也就是说整个字符串实际上是一行。如果需要在字符串中换行,可以在字符串中加入换行符"\n"。这种声明方式一般用在需要在代码中多行显示字符串以便提高可读性,例如:SQL语句往往需要多行显示来提高可读性、较长的文本的段落之间需要分行显示以便更容易找到分段位置。
此文将不断更新...
作者:黎波
博客:http://bobli.cnblogs.com/
日期:2011年12月7日