How to selectively trim an NSMutableString? - iphone

I would like to know how to selectively trim an NSMutableString. For example, if my string is "MobileSafari_2011-09-10-155814_Jareds-iPhone.plist", how would I programatically trim off everything except the word "MobileSafari"?
Note : Given the term programatically above, I expect the solution to work even if the word "MobileSafari" is changed to "Youtube" for example, or the word "Jared's-iPhone" is changed to "Angela's-iPhone".
Any help is very much appreciated!

Given that you always need to extract the character upto the first underscore; use the following method;
NSArray *stringParts = [yourString componentsSeparatedByString:#"_"];
The first object in the array would be the extracted part you need I would think.

TESTED CODE: 100% WORKS
NSString *inputString=#"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *array= [inputString componentsSeparatedByString:#"_"];
if ([array count]>0) {
NSString *resultedString=[array objectAtIndex:0];
NSLog(#" resultedString IS - %#",resultedString);
}
OUTPUT:
resultedString IS - MobileSafari

If you know the format of the string is always like that, it can be easy.
Just use NSString's componentsSeparatedByString: documented here.
In your case you could do this:
NSString *source = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *seperatedSubStrings = [source componentsSeparatedByString:#"_"];
NSString *result = [seperatedSubStrings objectAtIndex:0];
#"MobileSafari" would be at index 0, #"2011-09-10-155814" at index 1, and #"Jareds-iPhone.plist" and at index 2.

Try this :
NSString *strComplete = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *arr = [strComplete componentsSeparatedByString:#"_"];
NSString *str1 = [arr objectAtIndex:0];
NSString *str2 = [arr objectAtIndex:1];
NSString *str3 = [arr objectAtIndex:2];
str1 is the required string.
Even if you change MobileSafari to youtube it will work.

So you'll need an NSString variable that'll hold the beginning of the string you want to truncate. After that one way could be to change the string and the variable string values at the simultanously. Say, teh Variable string was "Youtube" not it is changed to "MobileSafari" then the mutable string string should change from "MobileSafari_....." to "YouTube_......". And then you can get the variable strings length and used the following code to truncate the the mutable string.
NSString *beginningOfTheStr;
.....
theMutableStr=[theMutableStr substringToIndex:[beginningOfTheStrlength-1]];
See if tis works for you.

Related

Json Values on Screen Objective c

NSDictionary *allDatDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *responseData = [allDatDictionary objectForKey:#"responseData"];
NSDictionary *arrayOfResult = [responseData objectForKey:#"results"];
for (NSDictionary *diction in arrayOfResult) {
NSString *title = [diction objectForKey:#"title"];
NSString *content = [diction objectForKey:#"content"];
NSString *url = [diction objectForKey:#"url"];
[array addObject:title];
[content1 addObject:content];
[url1 addObject:url];
NSLog(#"title: %#, \n Content: %# \n, Url: %# \n", [diction objectForKey:#"title"], [diction objectForKey:#"content"],[diction objectForKey:#"url"]);
NSString *text = #"";
text = [NSString stringWithFormat:#"Title: %#%#\nURL: %#\nContent: %#\n\n", text, [diction objectForKey:#"title"],[diction objectForKey:#"url"],[diction objectForKey:#"content"]];
Hey guys, I got the json and I need to show title, content and url on screen. I don't need table ranting like this just show on screen. NSLog shows everything but when I try to write on a UILabel it just shows 1 result. Any tips how I can do that? thanks
You're setting labelTitle's text in a for loop, so you're only going to see the last result, because you keep changing it each time thru the loop. If you want to see all of the results, you'll have to build up a string that contains all of them and then set that as the text of the label.
At the top of the for loop, declare an NSString variable and set it to #"", like the following:
NSString *text = #"";
Then each time thru the loop, instead of setting the label text to your string, build up this string that you're saving at the top, like the following:
text = [NSString stringWithFormat:#"%#%#\n", text, [diction objectForKey:#"title"]];
You can see how I modified that format string. It takes the previous text you've saved, adds to it your new title, and then adds a carriage return.
As an alternative, you could have an NSMutableArray at the top, and add your strings to that array each time you go thru the for loop. Then at the end, you can use the NSArray method componentsJoinedByString:, using a carriage return as the separator, to get an NSString containing all of the individual strings that you added to the array.
After you have this one string, using either of these methods, you can set that as the text on the label.

Simple NSDateFormatter / String Parse

2012-10-12 19:29:43
Aquivalent NSDateFormatter:
[_dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
Throws an exception ... Why?
Thank you!
Reference: http://waracle.net/mobile/iphone-nsdateformatter-date-formatting-table/
UPDATE:
The problem seems to be the string. If I hardcode the string:
NSString * string = #"2012-10-12 19:29:43";
It works fine.
I read it from an array of key-value pairs so I do:
NSString * string = [NSString stringWithFormat:#"%#", (NSString *)[[NSArray readFromPlistFile:#"latestchangesdates"] valueForKey:#"newsLastEdited"]];
Console Output:
#1:
2012-10-12 10:16:49
#2:
( "2012-10-12 10:16:49" )
I think the problem is something which has to do with the string parse from the array.
UPDATE 2:
[[[NSArray readFromPlistFile:#"latestchangesdates"] objectAtIndex:0] valueForKey:#"newsLastEdited"]]
... finally did it.
It looks like the key newsLastEdited in your Plist file is actually returning an array not a string.
The line:
NSString *string = [NSString stringWithFormat:#"%#", (NSString *)[[NSArray readFromPlistFile:#"latestchangesdates"] valueForKey:#"newsLastEdited"]];
is simply casting to an NSString the returned value from [[NSArray readFromPlistFile:#"latestchangesdates"] valueForKey:#"newsLastEdited"]. This does not automatically make the returned value a string.
What happens if you use the following instead:
NSString *string = [[[NSArray readFromPlistFile:#"latestchangesdates"] valueForKey:#"newsLastEdited"] objectAtIndex:0];
If I'm correct, this will take the first element of the array returned from the Plist newsLastEdited key. If this works then you should probably take some time to understand the data structure stored in the Plist file.
[[[NSArray readFromPlistFile:#"latestchangesdates"] objectAtIndex:0] valueForKey:#"newsLastEdited"]]
... finally did it.

variable is not a CFStringRef

I have this:
partenaire_lat = 48.8160525;
partenaire_lng = 2.3257800;
And obtain a NSString like this:
NSString *endPoint =[NSString stringWithFormat:#"%#,%#", partenaire_lat, partenaire_lng];
and after using this NSString in some context I get this stupid error:
Variable is not a CFString.
But if I create the NSString like this:
endPoint = #"48.8160525,2.3257800" it then works perfect!
For this error Variable is not a CFString I tried the following:
NSString *endPoint1 =[NSString stringWithFormat:#"%#,%#", partenaire_lat, partenaire_lng];
CFStringRef endPoint =(CFStringRef)endPoint1;
and tried to use endPoint but not working neither this way.Anyone any miraculous idea?Thx
EDIT:partenaire_lat and partenaire_lng are both NSString!!
You have
partenaire_lat = 48.8160525;
partenaire_lng = 2.3257800;
You keep saying that the two variables are NSStrings but you aren't assigning NSStrings to them. You need to assign NSString objects to NSString variables - they aren't created for you automatically.
So the answers which are telling you to use formatted strings are correct. You really should be doing it like this:
partenaire_lat = [[NSString stringWithFormat:#"%f", 48.8160525] retain];
partenaire_lng = [[NSString stringWithFormat:#"%f", 2.3257800] retain];
what are lat and lng? i'm assuming float or double..so you should use [NSString stringWithFormat:#"%f,%f", lat, lng]; (or however you want the floats to be formatted)
You code has several potential problems:
%# format specifier expects object parameter, while it looks like you pass plain float (I may be wrong here as there's not enough context to be sure). Change format to %f to fix your problem if that's really the case:
NSString *endPoint1 =[NSString stringWithFormat:#"%f,%f", partenaire_lat, partenaire_lng];
Your endPoint1 string is autoreleased and may become invalid outside of current scope if you don't retain it. So if you try to use your variable in another method you probably should retain it.
All you need to do
NSString *latStr=[[NSNumber numberWithFloat:partenaire_lat] stringValue];
NSString *lngStr=[[NSNumber numberWithFloat:partenaire_lng] stringValue];
and do whatever you want to do with these two string :)

writing NSString type to a file

I'm implementing the following function on appdelegate,
but I need to write NSString type instead of typical float values.
Since xcode doesn't allow an object to be in my desired position,
I used char* instead as follows, where as my data to be passed are of type NSString.
As expected, it doesn't work...
How could I manipulate it so that I could write NSString data type?
Should I make some conversion?
Please help me out..
- (void)addHallOfFamer:(char*)newHofer{
[hofArray addObject:[NSString stringWithFormat:#"%#",newHofer]];
[hofArray sortUsingSelector:#selector(compare:)];
NSArray* paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* hofArrayPath = [documentsDirectory
stringByAppendingPathComponent:#"hofers.plist"];
[hofArray writeToFile:hofArrayPath atomically:YES];
}
(added)
following is how I'm calling the written NSStrings from another view, which doesn't reflect my updating.
MainAppDelegate* delegate;
delegate = (MainAppDelegate*)[[UIApplication sharedApplication] delegate];
NSArray *hofers = [[delegate.hofArray reverseObjectEnumerator] allObjects];
hoferName1.text = [NSString stringWithFormat:#"%#",[hofers objectAtIndex:0]];
First, with the current char * argument, you need to use %s as your format directive, not %#.
Second, to use an NSString * as your argument, just add it to hofArray.
The easiest solution would be to just save the array in NSUserDefaults. Since it is an array of strings, saving and retrieving it that way should work fine and would be easier than dealing with the iOS filesystem.
Edit:
If you really want to save it in the filesystem, look into the NSKeyedArchiver method + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path and the NSKeyedUnarchiver method + (id)unarchiveObjectWithFile:(NSString *)path.
Edit 2:
As ondmike pointed out, you need to use %s rather than %# for your -stringWithFormat: method call to work properly. Relevant documentation is String Format Specifiers

How to concatenate two strings on iPhone?

How to connect string "Hello" and string "World" to "HelloWorld"? Looks like "+" doesn't work.
NSString *string = [NSString stringWithFormat:#"%#%#", #"Hello", #"World"];
NSLog(#"%#", string);
That should do the trick, although I am sure there is a better way to do this, just out of memory. I also must say this is untested so forgive me. Best thing is to find the stringWithFormat documentation for NSString.
How about:
NSString *hello = #"Hello";
NSString *world = #"World";
NSString *helloWorld = [hello stringByAppendingString:world];
If you have two literal strings, you can simply code:
NSString * myString = #"Hello" #"World";
This is a useful technique to break up long literal strings within your code.
However, this will not work with string variables, where you'd want to use stringWithFormat: or stringByAppendingString:, as mentioned in the other responses.
there's always NSMutableString..
NSMutableString *myString = [NSMutableString stringWithString:#"Hello"];
[myString appendString: #"World"];
Note:
NSMutableString *myString = #"Hello"; // won't work, literal strings aren't mutable
t3.text=[t1.text stringByAppendingString:t2.text];
Bill, I like yout simple solution and I'd like to note that you can also eliminate the space between the two NSStrings:
NSString * myString = #"Hello"#"World";