Sorting in NSHomeDirectory - ios

I have this code to save images in my app
NSString *fileName = [NSString stringWithFormat:#"2013_%d_a_%d",count,indexToInsert];
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[#"Documents/" stringByAppendingString:fileName]];
NSData *imageData = UIImagePNGRepresentation(imageToAdd);
[imageData writeToFile:pngPath atomically:YES];
in my log I see this:
"2013_10_a_1",
"2013_1_a_1",
"2013_2_a_1",
"2013_3_a_1",
"2013_4_a_1",
"2013_5_a_1",
"2013_6_a_1",
"2013_7_a_1",
"2013_8_a_1",
"2013_9_a_1"
why "2013_10_1" is on the top? it's in position 0, I want it at position 9 (10 elements)

The issue here is that the underscore character _ (ascii code 95) is sorted after any number character (ascii codes 48 to 57).
Change the output filename to include leading zero and you won't need to mess with sorting issues:
NSString *fileName = [NSString stringWithFormat:#"2013_%03d_a_%d",count,indexToInsert];
Will output:
"2013_001_a_1",
"2013_002_a_1",
"2013_003_a_1",
"2013_004_a_1",
"2013_005_a_1",
"2013_006_a_1",
"2013_007_a_1",
"2013_008_a_1",
"2013_009_a_1",
"2013_010_a_1"

Your strings contain numbers so you need to do a numeric sort, not a plain string sort. For this, use the compare:options: method on NSString with an option of NSNumericSearch.

Related

Get unicode chars from webservice and display them in ios app

I need some help:
i get from WebService only a part from the uunicode value, and after this I append the prefix \u to finish the value. The .ttf is good, i tested with some hardcoded values.
NSString *cuvant = [[self.catData objectAtIndex:indexPath.row]objectAtIndex:9]; //Get data
//apend prefix (double \ to escape the \u command)
cuvant = [NSString stringWithFormat:#"\\u%#",cuvant];
// cell.catChar.text = [NSString stringWithUTF8String:"\ue674"]; --->this works very well
cell.catChar.text = [NSString stringWithUTF8String:[cuvant UTF8String]]; //---> this doesn't work
i searched the documentation, and other sites but i didn't found nothing usefull, all the hints are with hardcoded data... i need tot take the codes dinamically
Thanks!
All you need is just to feed this unicoded string as data first. So make a C-String then
NSData *dataFromUnicodedString = [NSData dataWithBytes:yourCUnicodedString length:strlen(yourCUnicodedString)];
and afterwards the resulting string will be
NSString *unicodedString = [[NSString alloc] initWithData:dataFromUnicodedString encoding:NSUTF8StringEncoding];

How to convert string to utf8 encoding?

I am reading my app directory like this
NSArray *pathss = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorys = [pathss objectAtIndex:0];
NSError * error;
NSMutableArray * directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:documentsDirectorys error:&error];
the output i get:
"Forms_formatted.pdf",
"fund con u\U0308u\U0308.pdf",
"hackermonthly-issue.pdf",
these are the files name. my question, how come i able to convert this name "fund con u\U0308u\U0308.pdf" to correct format. thanks in advance
Maybe this will help:
NSString *documentsDirectorys = [pathss objectAtIndex:0];
const char *documentsDirectoryCstring = [documentsDirectorys cStringUsingEncoding:NSASCIIStringEncoding];
EDIT:
const char *documentsDirectoryCstring = [documentsDirectorys cStringUsingEncoding:NSUTF8StringEncoding];
Convert the NSString to NSData with UTF-16 encoding, convert back to a NSString with UTF-8 encoding.
It is probably UTF-16 big endian with no BOM. The character is not ASCII.
The character u\U0308 is not ASCII, it is a Combining Diacritical Mark ̈ü, the character is also known as double dot above, umlaut, Greek dialytika and double derivative. The \U0308 puts the umlaut above the u character.
You can try this. NSLog use description method of NSArray to print NSArray object, which deals with unicode characters differently than the description on objects its contains such as NSString objects. Or you can loop through the array and NSLog each item.
NSLog(#"%#", [NSString stringWithCString:[[array description] cStringUsingEncoding:NSASCIIStringEncoding] encoding:NSNonLossyASCIIStringEncoding]);

Getting more than char from string variable

I have an NSString *fileName
This will contain a variable number from 1 to 3 digits. I want to extract all of the digits
I can get the first digit using
//create text for appliance identifier
char obsNumber = [fileName characterAtIndex:3];//get 4 character
NSLog(#"Obs number %c",obsNumber);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c",obsNumber]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
However if the string contains the number for example 78, or 204 I want to catch all two or three digits.
I tried this
//create text for appliance identifier
char obsNumber1 = [fileName characterAtIndex:3];//get 4 character
char obsNumber2 = [fileName characterAtIndex:4];//get 5 character
char obsNumber3 = [fileName characterAtIndex:5];//get 6 character
NSLog(#"Obs number %c,%c,%c",obsNumber1,obsNumber2,obsNumber3);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c,%c,%c",obsNumber1,obsNumber2,obsNumber3]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
This gave me 18c 1ce etc
Would this work for you?
NSString *filename = #"obs127observation"; //An example variable with your format
This code could be tidier but you should get the idea:
NSString *filenameNumber = [[filename
stringByReplacingOccurrencesOfString:#"observation"
withString:#""]
stringByReplacingOccurrencesOfString:#"obs"
withString:#""];
you can trim other letters except the decimals.
NSString *onlyNumbers=[yourstring stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
As your comment says , It has predefined set of values, right. Then try like this
NSstring *str = [filename substringFromIndex:11];
// Convert the str to char[]
Then you should try with the NSScanner :
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:filename];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];
// Result.
int number = [numberString integerValue];
// you can play around with the set of number
Your approach of separating one character at a time and then combining them back into a string is an awkward, overly complex way of going about this. Kumar's suggestion of using NSScanner is a good option if you have a number in the middle of a string.
However, you make it sound like your string will always contain a number and only a number. Is that true? Or will there be characters you need to ignore?
You need to define the problem clearly and completely before you can select the best solution.
It might be as simple as using the NSString method substringWithRange.

How to read last n lines in a Text file in Objective C

I have a Text file and it has lot of lines How can i get last 'n' number of lines from the text file? and Can we give Numbers in the text file for each file How can we get it.
You could use NSFileHandle, seekToEndOfFile and then work backwards from the offsetInFile using seekToFileOffset: and readDataOfLength: scanning the data read each time for carriage returns and counting them until you get to the required number. As you go you can build up the text after each scan.
One way is putting \n to separate your different lines in the text file. Then
NSString* path = [[NSBundle mainBundle] pathForResource:#"filename"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSArray* lines = [content componentsSeparatedByString: #"\n"];
Then you can take the last few elements in the array.
Hope this helps..
Try to use this one:
NSString* textFile = [[NSBundle mainBundle]
pathForResource:#"fileName" ofType:#"txt"];
NSString* fileContents = [NSString stringWithContentsOfFile: textFile
encoding: NSUTF8StringEncoding error: nil];
Separate by new line
NSArray* allLinedStrings =
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
Here you can get your last 100 objects
NSString* oneLineStr;
for (int i = allLinedStrings.count - 100; i < allLinedStrings.count; i++)
{
oneLineStr = [allLinedStrings objectAtIndex: i];
NSLog#("New Line %#", oneLineStr);
}

Parsing and processing Text Strings in iOS

Wanted to find the best programming approach in iOS to manipulate and process text strings. Thanks!
Would like to take a file with strings to manipulate the characters similar to the following:
NQXB26JT1RKLP9VHarren Daggett B0BMAF00SSQ ME03B98TBAA8D
NBQB25KT1RKLP05Billison Whiner X0AMAF00UWE 8E21B98TBAF8W
...
...
...
Each string would process in series then loop to the next string, etc.
Strip out the name and the following strings:
Take the following 3 string fragments and convert to another number base. Have the code to process the new result but unsure of how to send these short strings to be processed in series.
QXB26
B0BM
BAA8
Then output the results to a file. The xxx represents the converted numbers.
xxxxxxxxx Harren Daggett xxxxxxxx xxxxxxxx
xxxxxxxxx Billison Whiner xxxxxxxx xxxxxxxx
...
...
...
The end result would be pulling parts of strings out of the first file and create a new file with the desired result.
There are several ways to accomplish what you are after, but if you want something simple and reasonably easy to debug, you could simply split up each record by the fixed position of each of the fields you have identified (the numbers, the name), then use a simple regular expression replace to condense the name and put it all back together.
For purposes like this I prefer a simple (and even a bit pedestrian) solution that is easy to follow and debug, so this example is not optimised:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *URLs = [fm URLsForDirectory: NSDocumentDirectory
inDomains: NSUserDomainMask];
NSURL *workingdirURL = URLs.lastObject;
NSURL *inputFileURL = [workingdirURL URLByAppendingPathComponent:#"input.txt" isDirectory:NO];
NSURL *outputFileURL = [workingdirURL URLByAppendingPathComponent:#"output.txt" isDirectory:NO];
// For the purpose of this example, just read it all in one chunk
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:inputFileURL
encoding:NSUTF8StringEncoding
error:&error];
if ( !stringFromFileAtURL) {
// Error, do something more intelligent that just returning
return;
}
NSArray *records = [stringFromFileAtURL componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
NSMutableArray *newRecords = [NSMutableArray array];
for (NSString *record in records) {
NSString *firstNumberString = [record substringWithRange:NSMakeRange(1, 5)];
NSString *nameString = [record substringWithRange:NSMakeRange(15, 27)];
NSString *secondNumberString = [record substringWithRange:NSMakeRange(43, 4)];
NSString *thirdNumberString = [record substringWithRange:NSMakeRange(65, 4)];
NSString *condensedNameString = [nameString stringByReplacingOccurrencesOfString:#" +"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, nameString.length)];
NSString *newRecord = [NSString stringWithFormat: #"%# %# %# %#",
convertNumberString(firstNumberString),
condensedNameString,
convertNumberString(secondNumberString),
convertNumberString(thirdNumberString) ];
[newRecords addObject: newRecord];
}
NSString *outputString = [newRecords componentsJoinedByString:#"\n"];
[outputString writeToURL: outputFileURL
atomically: YES
encoding: NSUTF8StringEncoding
error: &error];
In this example convertNumberString is a plain C function that converts your number strings. It could of course also be a method, depending on the architecture or your preferences.

Resources