1// NSStringExtension.m 2// Extension to NSString class 3// By lukhnos 4// This piece of code is public domain 5 6#import "NSStringExtension.h" 7 8@implementation NSString (SplitBySpaceWithQuote) 9+ (NSString*)stringByColor:(NSColor*)c { 10 return [NSString stringWithFormat:@"%f %f %f", [c redComponent], [c greenComponent], [c blueComponent]]; 11} 12- (NSColor*)colorByString { 13 NSArray *s=[self splitBySpaceWithQuote]; 14 if ([s count] < 3) return [NSColor blackColor]; 15 return [NSColor colorWithDeviceRed:[[s objectAtIndex:0] floatValue] green:[[s objectAtIndex:1] floatValue] blue:[[s objectAtIndex:2] floatValue] alpha:1.0]; 16} 17- (NSString*)stringByQuoting { 18 int l=[self length]; 19 UniChar *s=(UniChar*)calloc(1, l*sizeof(UniChar)); 20 [self getCharacters:s]; 21 UniChar *buf=(UniChar*)calloc(1, (l*2+2)*sizeof(UniChar)); 22 int i, p=0; 23 24 buf[p++]='\"'; 25 for (i=0; i<l; i++) { 26 if (s[i]=='\"') buf[p++]='\\'; 27 buf[p++]=s[i]; 28 } 29 buf[p++]='\"'; 30 NSString *r=[NSString stringWithCharacters:buf length:p]; 31 free(s); 32 free(buf); 33 return r; 34} 35- (NSString*)stringByChomping { 36 int i; 37 int l=[self length]; 38 if (!l) return [[NSString new] autorelease]; 39 40 for (i=l-1; i>=0; i--) { 41 if ([self characterAtIndex:i]!='\n') break; 42 } 43 44 if (i==-1) return [[NSString new] autorelease]; 45 NSRange r=(NSRange){0, i+1}; 46 return [self substringWithRange:r]; 47} 48- (NSArray*)splitBySpaceWithQuote { 49 NSMutableArray *ma=[[NSMutableArray new] autorelease]; 50 int p=0, q=0; 51 int l=[self length]; 52 UniChar *s=(UniChar*)calloc(1, l*sizeof(UniChar)); 53 [self getCharacters:s]; 54 UniChar *buf=(UniChar*)calloc(1, l*sizeof(UniChar)); 55 int bufp=0; 56 int emptystr=0; 57 58 while (p<l) { 59 // skip spaces 60 if (s[p]==32) p++; 61 62 // first non-space char 63 if (s[p]=='\"') { 64 q=1; 65 p++; 66 } 67 68 bufp=0; 69 emptystr=0; 70 while (p<l) { 71 if (!q && (s[p]==32 || s[p]=='\"')) break; 72 if (q && s[p]=='\"') { 73 q=0; 74 p++; 75 if (!bufp) emptystr=1; // make an emptystr regardless 76 break; 77 } 78 if (s[p]=='\\' && p+1 < l && s[p+1]=='\"') { 79 p+=2; 80 buf[bufp++]='\"'; 81 } 82 else buf[bufp++]=s[p++]; 83 } 84 85 if (bufp || emptystr) { 86 [ma addObject:[NSString stringWithCharacters:buf length:bufp]]; 87 } 88 } 89 90 free(s); 91 free(buf); 92 return ma; 93} 94@end 95 96