How do I create line breaks in a String I loaded from a textfile - ios

I want to load a simple text, like:
"first \n second"
My code is :
NSString *filePath = [[NSBundle mainBundle] pathForResource:path ofType:#"df"];
NSArray* allLines;
if (filePath) {
NSString* content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
allLines = [content componentsSeparatedByString:#"#"]; //Of course my text is separate with #
}else{
NSLog(#"%# didnt load", path);
}
for (int i = 0; i < [allLines count]; i++) {
[_textArray addObject:(NSString*)allLines[i]];
NSLog(#"Answer: %#",(NSString*)allLines[i]);
}
And I want to get this text on an UILabel. But I don't know how I can make this line breaks to work. :S

Instead of putting \n in the text file, put actual newlines in the text file. In other words, put "first" and "second" on two separate lines in the text file.

You wanted either of
label.text = [allLines componentsJoinedByString:#"\n"];
label.text = [content stringByReplacingOccurrencesOfString:#"#" withString:#"\n"];
But yes, just putting the newlines in the source file works fine too.

Related

Remove characters before dot

Im parsing html and now i got an NSString object that output like that:
imageName is 4tmp.jpg
imageName is 5tmp.jpg
imageName is 6tmp.jpg
imageName is 7tmp.jpg
imageName is 8tmp.jpg
imageName is 9tmp.jpg
And so on.
My code look like:
TFHpple *dataParseer = [TFHpple hppleWithHTMLData:data];
// 3
NSString *dataXpathQueryString = #"//head/title";
NSArray *dataNodes = [dataParseer searchWithXPathQuery:dataXpathQueryString];
TFHppleElement *element = dataNodes[0];
if ([element.text hasPrefix:#"Index of"]) {
dataXpathQueryString = #"//tr/td/a";
dataNodes = [dataParseer searchWithXPathQuery:dataXpathQueryString];
for (TFHppleElement *element in dataNodes){
NSString *imageName = [element objectForKey:#"href"];
NSLog(#"imageName is %#", imageName);
}
What i want is, remove characters before dot. So i can further concatenate it to correct url. How could i do that with NSString? Is there any method that can check characters before special symbol?
I'm not quite sure what exactly you want to get, but there are several ways to get values from string.
If you are working with path structures you can do something like this.
NSString *path = #"4tmp.jpg";
NSLog(#"1- %#",path.lastPathComponent);
NSLog(#"2- %#",[path.lastPathComponent stringByDeletingPathExtension]);
NSLog(#"3- %#",path.pathExtension);
Which will output something like
1- 4tmp.jpg
2- 4tmp
3- jpg
This will work obviously for more complex paths like "something/4tmp.jpg" in those cases the output will be the same as the one above
NSArray* stringComponents = [imageName componentsSeparatedByString:#"."];
imageName = [stringComponents objectAtIndex:1];

present NSString as a line of elements

I have an NSString that hold data (actually that could be presented an NSArray). and i want to output that on a label.
In NSLog my NSString output is:
(
"cristian_camino",
"daddu_02",
"_ukendt_babe_",
"imurtaza.zoeb"
)
What i want is, to present it like :"cristian_camino","daddu_02","_ukendt_babe_","imurtaza.zoeb"
In a single line.
I could accomplish that turning string to an array and do following: arrayObjectAtIndex.0, arrayObjectAtIndex.1, arrayObjectAtIndex.2, arrayObjectAtIndex.3.
But thats look not good, and that objects may be nil, so i prefer NSString to hold data.
So, how could i write it in a single lane?
UPDATE:
There is the method i want to use to set text for UILabel:
-(void)setLikeLabelText:(UILabel*)label{
//Likes
NSString* likersCount = [self.photosDictionary valueForKeyPath:#"likes.count"];
NSString* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent "likes": %#", likersCount, likersRecent];
label.text = textString;
NSLog(#"text String is %#", textString);
}
valueForKeyPath: returns an NSArray, not an NSString. Whilst you've declared likersCount and likersRecent as instances of NSString, they're actually both arrays of values. You should be able to do something like the following to construct a string:
NSArray* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *joined = [likersRecent componentsJoinedByString:#"\", \""];
NSString *result = [NSString stringWithFormat:#"\"%#\"", joined];
NSLog(#"Result: %#", result);
componentsJoinedByString: will join the elements of the array with ", ", and then the stringWithFormat call will add a " at the beginning and end.
The statement is incorrect, the internal quote marks (" that you want to display) need to be escaped:
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent \"likes\": %#", likersCount, likersRecent];
If somebody curious how i fix it, there it is:
for (int i =0; i < [likersRecent count]; i++){
stringOfLikers = [stringOfLikers stringByAppendingString:[NSString stringWithFormat:#" %#", [likersRecent objectAtIndex:i]]];
}
Not using commas or dots though.

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);
}

if statement with empty UILabel

I have a UILabel that is loaded form a text file. Sometimes the text file has something in it and sometimes it is empty. So sometimes the UILabel is blank and sometimes it has text in it.
I want to write an if statement that says if the UILabel is blank do one thing else if it has text in it do another thing.
I have tried
if (self.label.text = NULL)
and
if (self.label.text = #"")
but it isn't working correctly.
With the if (self.label.text = #""), I get the if statement to happen but the else statement doesn't work.
Here is my code
NSString *stuff3 = #"/Stuff";
NSString *titleName = [familyDictionary objectForKey:#"identity"];
NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
NSString *stuffPath3 = [documentsDirectory3 stringByAppendingPathComponent:stuff3];
NSString *fullPath3 = [stuffPath3 stringByAppendingPathComponent:titleName];
self.title = [NSString stringWithContentsOfFile:fullPath3 encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"full path 3 >>>%#",fullPath3);
NSString *stuff4 = #"/Stuff/Objects";
NSString *textName3 = [familyDictionary objectForKey:#"identity"];
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
NSString *stuffPath = [documentsDirectory2 stringByAppendingPathComponent:stuff4];
NSString *fullPath2 = [stuffPath stringByAppendingPathComponent:textName3];
self.wordlabel.text = [NSString stringWithContentsOfFile:fullPath2 encoding:NSUTF8StringEncoding error:NULL];
//Now load the image at fullPath and install it into our image view's image property.
NSLog(#"full path 3 >>>%#",fullPath2);
if(self.wordlabel.text = #"")
{
[textView setTitle:[NSString stringWithContentsOfFile:fullPath3 encoding:NSUTF8StringEncoding error:NULL] forState:UIControlStateNormal] ;
textView.titleLabel.adjustsFontSizeToFitWidth = TRUE;
}
else
{
[textView setTitle:[NSString stringWithContentsOfFile:fullPath2 encoding:NSUTF8StringEncoding error:NULL] forState:UIControlStateNormal] ;
textView.titleLabel.adjustsFontSizeToFitWidth = TRUE;
}
You're doing it wrong, wrong.
Wrong 1: = is the assignment operator, == is the equality operator. You're using the assignment operator inside an if statement, you should at least be getting a compiler warning about that.
Wrong 2: Even if you had that bit right, it's the wrong way to compare strings. Use isEqualToString: or check length as in the other answers.
Wrong 3: The logic should probably be based on the strings before you assign them to the label, not by reading back what is in the label. It's a cleaner MVC implementation.
What you are doing is comparing pointers, which doesn't work with strings. Use this
if ([self.wordlabel.text isEqualToString:#"thestring"])
you should ideally use:
if ([self.label.text length] > 0)
When you say self.label.text = #"" you are changing your label's text. = is the assignment operator. == is the comparison operator.
However, to compare strings, you must use the comparison method [self.label.text isEqualToString:#""], otherwise you are just comparing pointers.

IOS: stringByReplacingOccurrencesOfString don't work

filepath:/var/mobile/Applications/BA7AE6F8-C7EA-4601-A5F4-30E3C57FE948/Documents/photo2.jpg
photonumber:/var/mobile/Applications/BA7AE6F8-C7EA-4601-A5F4-30E3C57FE948/Documents/2
index = 2;
NSString *nextSequentialFile =
[filePath stringByReplacingOccurrencesOfString:photoNumber
withString:[NSString stringWithFormat:#"%d", index+1]
options:NSBackwardsSearch
range:NSMakeRange(0, filePath.length)];
the result is ever
nextsequenzial:/var/mobile/Applications/BA7AE6F8-C7EA-4601-A5F4-30E3C57FE948/Documents/photo2.jpg
why?
it must be /photo3.jpg
filepath doesn't contain photonumber, so there's nothing to replace. Note that photonumber ends with /Documents/2 while filepath contains /Documents/photo2.jpg.
photonumber needs to be changed to end in /Documents/photo2 and the replacement string needs to be changed to [NSString stringWithFormat:#"/photo%d", index+1].

Resources