NSArray *chunks = ... get an array, say by splitting it; string = [chunks componentsJoinedByString: @" :-) "];would produce something like
oop :-) ack :-) bork :-) greeble :-) ponies
NSString *string = @"oop:ack:bork:greeble:ponies"; NSArray *chunks = [string componentsSeparatedByString: @":"];
Similarly, there is a floatValue and doubleValue NSString methods.
-(NSUInteger) jacWordCount: (NSString *) string {
__block NSUInteger wordCount = 0;
[string enumerateSubstringsInRange:NSMakeRange(0, string.length)
options:NSStringEnumerationByWords
usingBlock:^(NSString *character, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
wordCount++;
}];
return wordCount;
}
(Muchos thankos to Jared Crawford for a more modern implementation)
NSAttributedString *string = ...;
NSRange totalRange = NSMakeRange (0, string.length);
[string enumerateAttributesInRange: totalRange
options: 0
usingBlock: ^(NSDictionary *attributes, NSRange range, BOOL *stop) {
NSLog (@"range: %@ attributes: %@",
NSStringFromRange(range), attributes);
}];
and if you're in 10.5 or earlier:
- (void) iterateAttributesForString: (NSAttributedString *) string
{
NSDictionary *attributeDict;
NSRange effectiveRange = { 0, 0 };
do {
NSRange range;
range = NSMakeRange (NSMaxRange(effectiveRange),
[string length] - NSMaxRange(effectiveRange));
attributeDict = [string attributesAtIndex: range.location
longestEffectiveRange: &effectiveRange
inRange: range];
NSLog (@"Range: %@ Attributes: %@",
NSStringFromRange(effectiveRange), attributeDict);
} while (NSMaxRange(effectiveRange) < [string length]);
} // iterateAttributesForStringLocalizable.strings that lives in your English.lproj directory (or whatever localization directory is appropriate). It has this syntax:
"BorkDown" = "BorkDown"; "Start Timer" = "Start Timer"; "Stop Timer" = "Stop Timer";That is, a key followed by a localized value.
In your code, you can then use NSLocalizedString() or one of its variants:
[statusItem setTitle: NSLocalizedString(@"BorkDown", nil)];The second argument is ignored by the function. Obstensively it is a
/* comment */ in the strings file so that you can match the key back to what it is supposed to actually be.NSlog puts too much crud in front of the logging line. For a foundation tool that output stuff, it gets in the way. I'd still like for a replacement to expand %@, which the printf() family won't do. Here's a some code that'll do that.
#include <stdarg.h>
void LogIt (NSString *format, ...)
{
va_list args;
va_start (args, format);
NSString *string;
string = [[NSString alloc] initWithFormat: format arguments: args];
va_end (args);
fprintf (stderr, "%s\n", [string UTF8String]);
[string release];
} // LogIt
- (NSAttributedString *) prettyName
{
NSTextAttachment *attachment;
attachment = [[[NSTextAttachment alloc] init] autorelease];
NSCell *cell = [attachment attachmentCell];
NSImage *icon = [self icon]; // or wherever you are getting your image
[cell setImage: icon];
NSString *name = [self name];
NSAttributedString *attrname;
attrname = [[NSAttributedString alloc] initWithString: name];
NSMutableAttributedString *prettyName;
prettyName = (id)[NSMutableAttributedString attributedStringWithAttachment:
attachment]; // cast to quiet compiler warning
[prettyName appendAttributedString: attrname];
return (prettyName);
} // prettyName
This puts the image at the front of the string. To put the image in the middle of the string, you'll need to create an attributedstring with attachment, and then append that to your final attributed string.
NSString *filebase = [baseName stringByReplacingOccurrencesOfString: @" "
withString: @""];
NSMutableString *mstring = [NSMutableString stringWithString:string];
NSRange wholeShebang = NSMakeRange(0, [mstring length]);
[mstring replaceOccurrencesOfString: @"
"
withString: @""
options: 0
range: wholeShebang];
return [NSString stringWithString: mstring];
(this can also be used for generic string manipulations, not just stripping out newlines).
This technique takes half the time (at least) of split/join. But probably not enough to make an impact. In a simple test, split/join took 0.124 seconds to strip 36909 newlines in a 1.5 meg textfile, and 0.071 seconds to do the same.
NSRange range = [[string name] rangeOfString: otherString options: NSCaseInsensitiveSearch];[[NSDate date] descriptionWithCalendarFormat: @"%B %e, %Y" timeZone: nil locale: nil](Thanks to Mike Morton for this one)
NSString *ook = @"\n \t\t hello there \t\n \n\n";
NSString *trimmed =
[ook stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"trimmed: '%@'", trimmed);
produces
2009-12-24 18:24:42.431 trim[6799:903] trimmed: 'hello there'
- (NSString *) truncateString: (NSString *) string
toCharacterCount: (NSUInteger) count {
NSRange range = { 0, MIN(string.length, count) };
range = [string rangeOfComposedCharacterSequencesForRange: range];
NSString *trunc = [string substringWithRange: range];
if (trunc.length < string.length) {
trunc = [trunc stringByAppendingString: @"..."];
}
return trunc;
} // truncateString
- (void) drawLabel: (NSString *) label
atPoint: (NSPoint) point
bold: (BOOL) bold {
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
NSFont *currentFont = [NSFont userFontOfSize: 14.0];
if (bold) {
NSFontManager *fm = [NSFontManager sharedFontManager];
NSFont *boldFont = [fm convertFont: currentFont
toHaveTrait: NSBoldFontMask];
[attributes setObject: boldFont
forKey: NSFontAttributeName];
} else {
[attributes setObject: currentFont
forKey: NSFontAttributeName];
}
[label drawAtPoint: point withAttributes: attributes];;
} // drawLabel
/usr/share/dict/words or from a script, and you want to process them. In this case turning a bunch of strings into floats:
NSMutableArray *altitudes = [NSMutableArray array];
NSString *altitudeString = [self altitudeStringFromGoogle: coords];
[altitudeString enumerateLinesUsingBlock: ^(NSString *line, BOOL *stop) {
float value = [line floatValue];
[altitudes addObject: [NSNumber numberWithFloat: value]];
}];
@implementation NSString (PasteboardGoodies)
- (void) sendToPasteboard
{
[[NSPasteboard generalPasteboard]
declareTypes: [NSArray arrayWithObject: NSStringPboardType]
owner:nil];
[[NSPasteboard generalPasteboard]
setString: self
forType: NSStringPboardType];
} // sendToPasteboard
@end // PasteboardGoodies
Thanks to Dan Jalkut for this tip.
func truncate(string: String, toCount count: Int) -> String {
if let endIndex = string.index(string.startIndex,
offsetBy: count,
limitedBy: string.endIndex) {
let range = string.startIndex ..< endIndex
let result = string[range]
if result == string { // It's exactly |count| thingies big
return string
} else {
return result + "..."
}
}
return string
}