[转载]NSString常用操作

字符串的使用
原文地址:NSString常用操作作者:iphone专家

//1、创建常量字符串。
    NSString *astring = @"This is a String!";

//2、创建空字符串,给予赋值。

    NSString *astring = [[NSString alloc] init];
    astring = @"This is a String!";
    NSLog(@"astring:%@",astring);
  [astring release];

//3、在以上方法中,提升速度:initWithString方法

    NSString *astring = [[NSString alloc] initWithString:@"This is a String!"];
    NSLog(@"astring:%@",astring);
    [astring release];

//4、用标准c创建字符串:initWithCString方法

    char *Cstring = "This is a String!";
    NSString *astring = [[NSString alloc] initWithCString:Cstring];
    NSLog(@"astring:%@",astring);
    [astring release];
    //5、创建格式化字符串:占位符(由一个%加一个字符组成)

    int i = 1;
    int j = 2;
    NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%d.This is %i string!",i,j]];
    NSLog(@"astring:%@",astring);
    [astring release];

    //6、创建临时字符串

    NSString *astring;
    astring = [NSString stringWithCString:"This is a temporary string"];
    NSLog(@"astring:%@",astring);

    NSString *path = @"astring.text";
    NSString *astring = [[NSString alloc] initWithContentsOfFile:path];
    NSLog(@"astring:%@",astring);
    [astring release];

    NSString *astring = [[NSString alloc] initWithString:@"This is a String!"];
    NSLog(@"astring:%@",astring);
    NSString *path = @"astring.text";   
    [astring writeToFile: path atomically: YES];
    [astring release];

    //用C比较:strcmp函数

    char string1[] = "string!";
    char string2[] = "string!";
    if(strcmp(string1, string2) = = 0)
    {
        NSLog(@"1");
    }

   //isEqualToString方法   
    NSString *astring01 = @"This is a String!";
    NSString *astring02 = @"This is a String!";
    BOOL result = [astring01 isEqualToString:astring02];
    NSLog(@"result:%d",result);

   //compare方法(comparer返回的三种值)   
    NSString *astring01 = @"This is a String!";
    NSString *astring02 = @"This is a String!";   
    BOOL result = [astring01 compare:astring02] = = NSOrderedSame;   
    NSLog(@"result:%d",result);   

    //NSOrderedSame 判断两者内容是否相同

    NSString *astring01 = @"This is a String!";
    NSString *astring02 = @"this is a String!";
    BOOL result = [astring01 compare:astring02] = = NSOrderedAscending;   

    NSLog(@"result:%d",result);

    //NSOrderedAscending 判断两对象值的大小(按字母顺序进行比较,astring02大于astring01为真)

    NSString *astring01 = @"this is a String!";
    NSString *astring02 = @"This is a String!";
    BOOL result = [astring01 compare:astring02] = = NSOrderedDescending;   
    NSLog(@"result:%d",result);    

    //NSOrderedDescending 判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真)

//不考虑大 小写比较字符串1
    NSString *astring01 = @"this is a String!";
    NSString *astring02 = @"This is a String!";
    BOOL result = [astring01 caseInsensitiveCompare:astring02] = = NSOrderedSame;   
    NSLog(@"result:%d",result);    

    //NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真)

//如何判断字符串为空

NSString *urlString = [urlInput stringValue];

if (!urlString) {

NSLog( @”NO INPUT.” );

} else {

if ([urlString length] == 0 ) {

NSLog( @”NO INPUT.” );

} else {

}
}
}

Convert NSString to int
1 NSString *aNumberString = @"123";
2 int i = [aNumberString intValue];

 

/////////////////////////////////////////////////

use @"abc" to mean NSString
ex: NSString *str = @"Hello";

use content of file to create NSString
ex: NSString *str = [NSString stringWithContentsOfFile:@"/path/to/file"]

use c characters to create NSString
ex: char *cStr="hello";
NSString *str = [NSString stringWithCString: cStr]

get length of NSString
ex: unsigned int strLen = [str length]

append on NSString to another
ex: NSString *str = @"Hello";
NSString *str2 = [str stringByAppendingString: @"abc"]

append a format:
ex: NSString *str3 = [str2 stringByAppendingFormat: @"%d", 2003]

search for subString:
ex: NSRange loc = [str rangeOfString:@"The"]

what is NSRange:
typedef struct _NSRange{
unsigned int location;
unsigned int length;
}NSRange;

breaking a string into components:
ex: NSArray *fields = [str componentsSeperatedByString:@"abc"];

create NSMutableString from NSString:
ex: NSString *str = @"hello";
NSMutableString *ms = [NSMutableString stringWithString: str];

/////////////////////////////////////////////////

 

1 合并一个字符串数组到单个字符串。

  1. NSArray *chunks = ... get an array, say by splitting it;
  2. string = [chunks componentsJoinedByString: @" :-) "];

输出结果如下:

  1. oop :-) ack :-) bork :-) greeble :-) ponies

2 将一个字符串分割成数组

  1. NSString *string = @"oop:ack:bork:greeble:ponies";
  2. NSArray *chunks = [string componentsSeparatedByString: @":"];

3 将字符串转换成整型数

  1. NSString *string = ...;
  2. int value = [string intValue];

同样NSString也有floatValue和doubleValue的方法。

4 遍历属性字符串(Attributed string)中的属性
如下函数可以打印出输入的属性字符串中的所有属性

  1. - (void) iterateAttributesForString: (NSAttributedString *) string
  2. {
  3. NSDictionary *attributeDict;
  4. NSRange effectiveRange = { 0, 0 };
  5. do {
  6. NSRange range;
  7. range = NSMakeRange (NSMaxRange(effectiveRange),
  8. [string length] - NSMaxRange(effectiveRange));
  9. attributeDict = [string attributesAtIndex: range.location
  10. longestEffectiveRange: &effectiveRange
  11. inRange: range];
  12. NSLog (@"Range: %@ Attributes: %@",
  13. NSStringFromRange(effectiveRange), attributeDict);
  14. } while (NSMaxRange(effectiveRange) < [string length]);
  15. }

5 制作本地化的字符串
你需要在English.lproj目录(或其他合适的本地化目录)中有一个名为Localizable.strings的文件。它有如下的语法:

  1. "BorkDown" = "BorkDown";
  2. "Start Timer" = "Start Timer";
  3. "Stop Timer" = "Stop Timer";

也就是,每个键值都有一个本地化的值。

在代码中,可以使用NSLocalizedString()或其变种。

  1. [statusItem setTitle: NSLocalizedString(@"BorkDown", nil)];

其中该函数忽略了第二个参数。

6 无多余信息的NSLog
NSlog在日志行之前输出了太多无关信息。对于一个用于输出的基础工具,它确实有点碍事。不过我仍然和喜欢printf()系列所不能的%@展开替换。如下是可以实现该功能的代码:

  1. #include <stdarg.h>
  2. void LogIt (NSString *format, ...)
  3. {
  4. va_list args;
  5. va_start (args, format);
  6. NSString *string;
  7. string = [[NSString alloc] initWithFormat: format arguments: args];
  8. va_end (args);
  9. printf ("%sn", [string cString]);
  10. [string release];
  11. }

7 在属性字符串中加入图片
我们需要使用一个文本附件:

  1. - (NSAttributedString *) prettyName
  2. {
  3. NSTextAttachment *attachment;
  4. attachment = [[[NSTextAttachment alloc] init] autorelease];
  5. NSCell *cell = [attachment attachmentCell];
  6. NSImage *icon = [self icon]; // or wherever you are getting your image
  7. [cell setImage: icon];
  8. NSString *name = [self name];
  9. NSAttributedString *attrname;
  10. attrname = [[NSAttributedString alloc] initWithString: name];
  11. NSMutableAttributedString *prettyName;
  12. prettyName = (id)[NSMutableAttributedString attributedStringWithAttachment:
  13. attachment]; // cast to quiet compiler warning
  14. [prettyName appendAttributedString: attrname];
  15. return (prettyName);
  16. }

这样就可以在字符串前面加入图片。如果需要在字符串中加入图片就需要创建通过附件创建一个属性字符串,然后将其加入到最终的属性字符串中。

8 除去字符串中的换行符
假定有一个字符串,你想除去换行符。你可以像脚本语言一样进行一个分割/合并操作,或者制作一个可变的拷贝并进行处理:

  1. NSMutableString *mstring = [NSMutableString stringWithString:string];
  2. NSRange wholeShebang = NSMakeRange(0, [mstring length]);
  3. [mstring replaceOccurrencesOfString: @"
  4. withString: @""
  5. options: 0
  6. range: wholeShebang];
  7. return [NSString stringWithString: mstring];

(这也可用于通用的字符串操作,不仅经是除去换行符)
该方法比分割/合并至少省一半的时间。当然可能结果不会造成太多的不同。在一个简单的测试中,处理一个1.5兆文件中36909个新行,分割/合并操作花费了0.124秒,而上述方法仅需0.071秒。

9 字串匹配

  1. NSRange range = [[string name] rangeOfString: otherString options: NSCaseInsensitiveSearch];

10 今天日期的字符串
将一个日期转换成字符串的通用方法就是通过NSDateFormatter。有时你想生成一个格式比较友好的日期字符串。比如你需要"December 4, 2007",这种情况下就可以使用:

  1. [[NSDate date] descriptionWithCalendarFormat: @"%B %e, %Y" timeZone: nil locale: nil]

(感谢Mike Morton提供该方法)

11 除去字符串末尾的空格

  1. NSString *ook = @"n tt hello there tn nn";
  2. NSString *trimmed =
  3. [ook stringByTrimmingCharactersInSet:
  4. [NSCharacterSet whitespaceAndNewlineCharacterSet]];
  5. NSLog(@"trimmed: '%@'", trimmed);

输出结果是:
2009-12-24 18:24:42.431 trim[6799:903] trimmed: 'hello there'

图形
1 绘制一个粗体字符串

  1. - (void) drawLabel: (NSString *) label
  2. atPoint: (NSPoint) point
  3. bold: (BOOL) bold {
  4. NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
  5. NSFont *currentFont = [NSFont userFontOfSize: 14.0];
  6. if (bold) {
  7. NSFontManager *fm = [NSFontManager sharedFontManager];
  8. NSFont *boldFont = [fm convertFont: currentFont
  9. toHaveTrait: NSBoldFontMask];
  10. [attributes setObject: boldFont
  11. forKey: NSFontAttributeName];
  12. } else {
  13. [attributes setObject: currentFont
  14. forKey: NSFontAttributeName];
  15. }
  16. [label drawAtPoint: point withAttributes: attributes];;
  17. }
原文地址:https://www.cnblogs.com/cnsec/p/11515885.html