iOS Read file lines into array - ios

I have a file containing a couple thousands words on individual lines. I need to load all of these words into separate elements inside an array so first word will be Array[0], second will be Array[1] etc.
I found some sample code elsewhere but Xcode 4.3 says it's using depreciated calls.
NSString *tmp;
NSArray *lines;
lines = [[NSString stringWithContentsOfFile:#"testFileReadLines.txt"]
componentsSeparatedByString:#"\n"];
NSEnumerator *nse = [lines objectEnumerator];
while(tmp = [nse nextObject]) {
NSLog(#"%#", tmp);
}

Yes, + (id)stringWithContentsOfFile:(NSString *)path has been deprecated.
See Apple's documentation for NSString
Instead use + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
Use as follows:
lines = [[NSString stringWithContentsOfFile:#"testFileReadLines.txt"
encoding:NSUTF8StringEncoding
error:nil]
componentsSeparatedByString:#"\n"];
Update: - Thanks to JohnK
NSCharacterSet *newlineCharSet = [NSCharacterSet newlineCharacterSet];
NSString* fileContents = [NSString stringWithContentsOfFile:#"testFileReadLines.txt"
encoding:NSUTF8StringEncoding
error:nil];
NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:newlineCharSet];

Check this. You might have to use an updated method.

Related

Getting multiple tags from html source code in Objective-C

I have extracted the source code from a website but i would like to display the strings of three urls. I have managed to strip the code so the only url's are the ones I need. How can I get the three strings in an array. The URL's look like this: Example
where I need to extract the string: 'example'
I have tried the NSScanner but without any luck. Please advice
Not the most clever way, but you can get the first approach of > and then the first < from there. All with standard NSString methods like rangeOfString: and such.
This code with NSScanner should give you luck :)
-(NSMutableArray *)yourStringArrayWithHTMLSourceString:(NSString *)html {
NSString *from = #"<a href=\"";
NSString *to = #"</a>";
NSMutableArray *array = [[NSMutableArray alloc]init];
NSScanner* scanner = [NSScanner scannerWithString:html];
for(int x=0;x<3;x++) {//You said only 3 strings
NSString *tempString;
[scanner scanUpToString:from intoString:nil];
[scanner scanString:from intoString:nil];
[scanner scanUpToString:to intoString:&tempString];
NSString *str = [tempString substringFromIndex:[tempString rangeOfString:#"\">"].location+2];
[array addObject:str];
}
return array;
}
usage:
for example:
NSString *html = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://facebook.com"] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#",[self yourStringArrayWithHTMLSourceString:html]);//will return NSMutableArray
Here is how to convert NSMutableArray to NSArray if you would like to to that:
NSArray *array = [NSArray arrayWithArray:mutableArray];

How to concatenate TextView.text

I have two UITextViews:
self.itemsTextView.text;
self.priceTextView.text;
I want to concatenate these two like so:
NSString *data = self.textView.text + self.itemsTextView.text;
I have tried using a colon, as suggested by this thread, but it doesn't work.
NSString *data = [self.textView.text : self.itemsTextView.text];
For concatenating you have several options :
Using stringWithFormat:
NSString *dataString =[NSString stringWithFormat:#"%#%#",self.textView.text, self.itemsTextView.text];
Using stringByAppendingString:
NSMutableString has appendString:
You may use
NSString * data = [NSString stringWithFormat:#"%#%#",self.textView.text,self.itemsTextView.text];
There are so many ways to do this. In addition to the stringWithFormat: approaches of the other answers you can do (where a and b are other strings):
NSString *c = [a stringByAppendingString:b];
or
NSMutableString *c = [a mutableCopy];
[c appendString b];

remove append strings

I have an nsarray with strings like this,
albumname/song42.mp3
albumname/song43.mp3 etc .
I want to remove the string "album name" and ".mp3" from the above array,and display it in a tableview as follows ,
song42
song43
then in the DidSelectRow ,i want to add the string
"http://www.domain.com/albumname/" and ".mp3" to the indepath.row element .
fo eg :
if user selects song42 in tableview ,then it must create a string like this "http://www.domain.com/albumname/song42.mp3"
How to do this ?
- [NSString stringByDeletingPathExtension] <--- This to remove
+ [NSString stringWithFormat:] <--- And this to recreate
EDIT My mistake, you first need to do this before you call the first method:
NSString *lastPath = [string lastPathComponent]; //song43.mp3
NSString *tableString = [lastPath stringByDeletingPathExtension]; //song43
You can use lastPathComponent and stringByDeletingPathExtension methods:
NSMutableArray *songs = [NSArray arrayWithCapacity:[sourceArray count]];
for (NSString *filename in sourceArray) {
[songs addObject:[[filename lastPathComponent] stringByDeletingPathExtension]];
}
use the String method componentsSeparatedByString first separate the strings using / and then . and discard what you don't need.
NSString *str="albumname/song42.mp3";
NSArray *mainStrArray = [str componentsSeparatedByString:#"/"];
NSArray remainingStrArray=[[mainStrArray objectAtIndex:1]componentsSeparatedByString:#"."];
NSString *result=[remainingStrArray objectAtIndex:0]; //here you have song42
You can use, as :
NSString *str = #"album name/song43.mp3";
str=[[str componentsSeparatedByString:#"/"][1]componentsSeparatedByString:#".mp3"][0];
NSLog(#"->%#",str); //song43
NSString *file = #"albumname/song42.mp3";
NSString *name = [[[[file componentsSeparatedByString:#"/"] objectAtIndex:1] componentsSeparatedByString:#"."] objectAtIndex:0];

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.

How do I parse a NSString?

I have a string
https://gdata.youtube.com/feeds/api/videos?q=4s-PbMuNooo
I want to get string 4s-PbMuNooo. How do I parse a NSString?
Short answer :
NSString *myString = #"https://gdata.youtube.com/feeds/api/videos?q=4s-PbMuNooo";
NSArray *components = [myString componentsSeparatedByString:#"="];
NSString *query = [components lastObject];
Problems :
1) What if the bit after the q= contains another =
2) What if the q= bit is missing?
A better answer is for you to read the documentation - there are lots of helper methods on NSString that will get you substrings. Look for rangeOfString to find out where the equals would be and subStringWithRange to get the bit you want.
EDIT: Thomas has raised a fair point about URL parsing - see his answer here
A slightly longer but more complete answer. Hope this helps:
NSURL *url = [NSURL URLWithString: #"https://gdata.youtube.com/feeds/api/videos?param1=yeah&param2="];
NSArray *listItems = [[url query] componentsSeparatedByString:#"&"];
NSMutableDictionary *keyValues = [NSMutableDictionary dictionaryWithCapacity:listItems.count];
for (NSString *item in listItems) {
NSArray *keyValue = [item componentsSeparatedByString:#"="];
NSAssert(keyValue.count == 2, #"Key value pair mismatch");
[keyValues setObject:[keyValue objectAtIndex:1] forKey:[keyValue objectAtIndex:0]];
}
NSLog(#"1: %#", [keyValues objectForKey:#"param1"]);
NSLog(#"2: %#", [keyValues objectForKey:#"param2"]);
Like this:
NSArray *listItems = [yourString componentsSeparatedByString:#"="];
NSString *myFinalString=[NSString stringWithString:[listItems objectAtIndex:1]];
I wanted to try this a bit, so here is my code that handles more than one parameters:
NSURL *url = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/videos?p=123123&q=234"];
NSArray *queryArray = [[url query] componentsSeparatedByString:#"&"];
for (NSString *queryString in queryArray) {
NSArray *queryComponents = [queryString componentsSeparatedByString:#"="];
if ([[queryComponents objectAtIndex:0] isEqualToString:#"q"]) {
NSLog(#"Found q: %#", [queryString substringFromIndex:2]);
} else {
NSLog(#"Did not find q.");
}
}
The question and its title are badly chosen - the answers are generally right for the more general task of splitting ANY string up, but bad for splitting up URLs as this question is actually about.
Here's how to properly get the values from a URL:
To break up a URL string, first do this:
NSURL *url = [NSURL URLWithString:urlString];
Then retrieve the parameters (the part past the "?") like this:
NSString *query = [url query];
Now you can go ahead and split that query string up using componentsSeparatedByString:#"&" as shown in the other answers.

Resources