finding word after the match using NSString - macos

I have varius log files to read. Each logs contain a report of a devices (printers).
What I can find is always the word 'firmware:' followed by the firmware revision like:
PTRE firmware: XER8673B2
The log does not seem to be very ordered, whereby the position of this text is not always on the same point or on the same line, but is always in the "PTRE firmawre: XXXXXXX" format.
How can I find XER8673B2 ? Any help is appreciated.
SOLVED (thanks to #roman-sausarnes), this is the code:
NSString *stringToSearch = [[NSString alloc] initWithContentsOfFile:#"path/to/log" encoding:NSUTF8StringEncoding error:nil];
NSString *preMatchString = #"PTRE firmware: ";
NSString *terminatingCharacter = #" ";
NSString *result = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:stringToSearch];
[scanner scanUpToString:preMatchString intoString:NULL];
[scanner scanString:preMatchString intoString:NULL];
[scanner scanUpToString:terminatingCharacter intoString:&result];
NSLog(#"It's : %#", result);
The output is
It's : XER8673B2

Look at NSScanner. The code would look something like this:
NSString *stringToSearch = theStringThatYouWantToSearch;
NSString *preMatchString = #"firmware: ";
NSString *terminatingCharacter = " ";
NSString *result = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:stringToSearch];
[scanner scanUpToString:preMatchString intoString:NULL];
[scanner scanString:preMatchString intoString:NULL];
[scanner scanUpToString:terminatingCharacter intoString:&result];
At the end, result should be the string that came after "firmware: " but before the next trailing space (" ").

Related

Extract numbers from NSString

How can I extract numbers from a string defined like:
NSString *getNumber = #"Price138.50 Code112.250"
I need to extract both 138.50 and 112.25 from this string.
Use NSScanner, slightly modified from this Apple example:
NSCharacterSet *numberCharset = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"];
NSScanner *theScanner = [NSScanner scannerWithString:aString];
while (![theScanner isAtEnd]) {
// Eat non-digits and negative sign
[theScanner scanUpToCharactersFromSet:numberCharset
intoString:NULL];
float aFloat;
if ([theScanner scanFloat:&aFloat]) {
NSLog(#"Found %f", aFloat);
}
}
NSString *getNumber = #"Price138.50 Code112.250";
getNumber = [getNumber stringByReplacingOccurrencesOfString:#"Price" withString:#""];
getNumber = [getNumber stringByReplacingOccurrencesOfString:#"Code" withString:#""];
getNumber = [getNumber stringByReplacingOccurrencesOfString:#" " withString:#","];
NSArray *values = [getNumber componentsSeparatedByString:#","];
NSLog(#"Price Value: %#", [values firstObject]);
NSLog(#"Code Value: %#", [values lastObject]);
If your string will be of same kind then this can be a possible way. Not Recommended.

How to print properly accents when logging an NSArray?

The following code
NSString * firstString = #"à" ;
NSString * secondString = #"é" ;
NSArray * myArray = #[firstString, secondString] ;
NSLog(#"%# and %#", firstString, secondString) ;
NSLog(#"%#", myArray) ;
prints out
TestAccentsArray[3883:303] à and é
TestAccentsArray[3883:303] (
"\U00e0",
"\U00e9"
)
Is there a way to print properly accents when logging an NSArray?
PS : I want to log the NSArray if possible. I know that with a loop and logging the elements of the NSArray it will work.
Try this :
for (NSString *str in myArray) {
NSLog(#"%#", str) ;
}

AVSpeechSynthesizer - How to detect dot for milliseconds pause (iPHONE - iPAD / iOS7 xcode)

I want to read a very long text:
NSString *text =#"Long test with dot. I want speaching pause when read dot. How can I do?";
AVSpeechSynthesizer *synthesizer = [AVSpeechSynthesizer new];
[synthesizer setDelegate:self];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:[self.defaults objectForKey:LANGUAGE]];
utterance.rate = 0.28;
[synthesizer speakUtterance:utterance];
I want synthesizer detect dot and pause for 100 millisecond.
Is it possible? How can I do ??
I mean a dot (.)
but maybe I found a solution also fot char ',' :
NSString *text = #"Line one. LineTwo aftre a pause. Line three, pause here again.";
text = [text stringByReplacingOccurrencesOfString:#"," withString:#"."];
NSArray *a = [text componentsSeparatedByString:#"."];
for(NSString *line in a)
{
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:line];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:[self.defaults objectForKey:LINGUA]];
utterance.rate = 0.28;
utterance.**postUtteranceDelay** = 0.3;
[self.synthesizer speakUtterance:utterance];
}

Sort by Double Value and not String Value

I'm currently pulling info from an sql DB where the 'cachedDist' column is set as a double. However when I pull it into my app and create my array I turn it into an String and the sort will obviously be off, 18.15 will come before 2.15. How do I fix that in my code so it will sort distance as a Double and not a String?
In Bar object.
NSString *cachedDist
#property(nonatomic,copy) NSString *cachedDist;
#synthesize cachedDist;
My while loop in the View Controller.
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Bar * bar = [[Bar alloc] init];
bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
bar.barCity = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
bar.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
bar.barZip = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)];
bar.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)];
bar.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)];
if (currentLoc == nil) {
NSLog(#"current location is nil %#", currentLoc);
}else{
CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[bar.barLat doubleValue] longitude:[bar.barLong doubleValue]];
bar.cachedDist = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000];
[thebars addObject:bar];
}
My sorting
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"cachedDist" ascending:YES];
sortedArray = [thebars sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
return sortedArray;
NSString has a method doubleValue to make this quite simple:
double cachedDistance = [cachedDistanceString doubleValue];
which you can use in a custom comparator for your sorting, or else make the property an NSNumber or double to make sorting that much easier. (I'm not sure how you are sorting...)
edit:
I re-evaluated your code, and now it looks like we are going from a double to a string to a double... we can cut out the middle-man, so to speak.
In your #prototype section, change the #property:
// #property(nonatomic,copy) NSString *cachedDist; // old way
#property(nonatomic) double cachedDist;
then assign it like this:
bar.cachedDistance = [currentLoc distanceFromLocation: barLocation]/1000;
and remove the lines which create a string from the distance (which is actually just a double).
Alternatively, if you want to be more object oriented, you can (should?) use NSNumber objects:
#property(nonatomic,copy) NSNumber *cachedDist;
...
bar.cachedDistance = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000];

Cocoa - Trim all leading whitespace from NSString

(have searched, but not been able to find a simple solution to this one either here, or in Cocoa docs)
Q. How can I trim all leading whitespace only from an NSString? (i.e. leaving any other whitespace intact.)
Unfortunately, for my purposes, NSString's stringByTrimmingCharactersInSet method works on both leading and trailing.
Mac OS X 10.4 compatibility needed, manual GC.
This creates an NSString category to do what you need. With this, you can call NSString *newString = [mystring stringByTrimmingLeadingWhitespace]; to get a copy minus leading whitespace. (Code is untested, may require some minor debugging.)
#interface NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace;
#end
#implementation NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace {
NSInteger i = 0;
while ((i < [self length])
&& [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[self characterAtIndex:i]]) {
i++;
}
return [self substringFromIndex:i];
}
#end
This is another solution using Regular Expressions (requires iOS 3.2):
NSRange range = [string rangeOfString:#"^\\s*" options:NSRegularExpressionSearch];
NSString *result = [string stringByReplacingCharactersInRange:range withString:#""];
And if you want to trim the trailing whitespaces only you can use #"\\s*$" instead.
This code is taking blanks.
NSString *trimmedText = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",trimmedText);
Here is a very efficient (uses CoreFoundation) way of doing it (Taken from kissxml):
- (NSString *)trimWhitespace {
NSMutableString *mStr = [self mutableCopy];
CFStringTrimWhitespace((CFMutableStringRef)mStr);
NSString *result = [mStr copy];
[mStr release];
return [result autorelease];
}
NSString *myText = #" foo ";
NSString *trimmedText = [myText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"old = [%#], trimmed = [%#]", myText, trimmedText);
Here's what I would do, and it doesn't involve categories!
NSString* outputString = inputString;
NSRange range = [inputString rangeOfCharacterFromSet: [NSCharacterSet whitespaceCharacterSet]
options:0];
if (range.location == 0)
outputString = [inputString substringFromIndex: range.location + range.length];
This is much less code.
I didn't really have much time to test this, and I'm not sure if 10.4 contains the UTF8String method for NSString, but here's how I'd do it:
NSString+Trimming.h
#import <Foundation/Foundation.h>
#interface NSString (Trimming)
-(NSString *) stringByTrimmingWhitespaceFromFront;
#end
NSString+Trimming.m
#import "NSString+Trimming.h"
#implementation NSString (Trimming)
-(NSString *) stringByTrimmingWhitespaceFromFront
{
const char *cStringValue = [self UTF8String];
int i;
for (i = 0; cStringValue[i] != '\0' && isspace(cStringValue[i]); i++);
return [self substringFromIndex:i];
}
#end
It may not be the most efficient way of doing this but it should work.
str = [str stringByReplacingOccurrencesOfString:#" " withString:#""];

Resources