I am writing a string tokenizer in Objective-C for an iPhone application.
I have the result as:
1|101|Y|103|Y|105|Y|107|Y|109|Y|111|Y|113|Y|115|Y|
I want to tokenize this string and display each of the values in tabular format. How am I to do it?
I want the result in a tabular format. Like:
102 Y
103 Y
.. ...
If by “tokenizing” you mean simply “splitting on the pipe-sign”, you can use the componentsSeparatedByString: method of NSString:
NSString *original = #"1|101|Y|103|Y|105…";
NSArray *fields = [original componentsSeparatedByString:#"|"];
“Displaying in a tabular format” doesn’t say much. If you want a classic table, see the UITableView class.
Not sure why you want this specifically in Objective-C (are you looking for a
tokenizer class?), but generic strsep() resp. iso-c90 strtok() / strtok_r() do this and they exist on Mac OS X and on iPhone OS. Described here:
http://developer.apple.com/iPhone/library/documentation/System/Conceptual/ManPages_iPhoneOS/man3/strsep.3.html
These got code quotes as well.
NSString *string = #"1|101|Y|103|Y|105|Y|107|Y|109|Y|111|Y|113|Y|115|Y|";
NSArray *chunks = [string componentsSeparatedByString: #"|"];
Related
I have NSMutableArray like :
NSMutableArray *x=[[NSMutableArray alloc]initWithObjects:#"a",#"b",#"c",#"d", nil];
NSLog(#"%#",x.description);
From the description I got the following result :
(
a,
b,
c,
d
)
I want to again recreate the array from the description is it possible ?
There is no way that would reliably work in all cases. For example, you cannot know if
(
123
)
represents an array containing a string or a number.
Added: There actually is a method to convert the description back to an array object (but it does not always return an identical array for the reason given above). The description method of NSArray and NSDictionary
uses the Old-Style ASCII Property Lists format which can be read using NSPropertyListSerialization:
NSArray *a1 = #[#"123", #456];
NSString *desc = [a1 description];
NSData *d = [desc dataUsingEncoding:NSUTF8StringEncoding];
NSArray *a2 = [NSPropertyListSerialization propertyListWithData:d
options:0
format:NULL
error:NULL];
NSLog(#"%#", a2);
NSLog(#"a1[1] is a %#", [a1[1] class]);
NSLog(#"a2[1] is a %#", [a2[1] class]);
Output:
(
123,
456
)
a1[1] is a __NSCFNumber
a2[1] is a __NSCFString
As you can see, the array a2 looks like a1, but the second element 456, which was a NSNumber originally, has been read back as a NSString.
So you should use description only as a debugging tool. Better methods to create a reversible human-readable description or an archive have been mentioned in the other answers and comments.
While you could, it's not why NSLog() exists. NSLog's purpose is to give a simple error logging mechanism for developers.
You should read into other means of storing data :
Saving to file via NSData.
Using Core Data
NSCoder
Various JSON serializers/parsers.
etc.
But if you really want to, you could parse a log file manually. (With NSRegularExpressions perhaps, NSScanner, etc.)
hey just a couple quick noob questions about writing my first ios app. Ive been searching through the questions here but they all seem to address questions more advanced than mine so im getting confused.
(1) All I want to do is turn a string into an array of integers representing the ASCII code. In other words, I want to convert:
"This is some string. It has spaces, punctuation, AND capitals."
into an array with 62 integers.
(2) How do I get back from the NSArray to a string?
(3) Also, are these expensive operations in terms of memory or computation time? It seems like it might be if we have to create a new variable at every iteration or something.
I know how to declare all the variables and im assuming I run a loop through the length of the string and at each iteration I somehow get the character and convert it into a number with some call to a built in command.
Thanks for any help you can offer or links to posts that might help!
if you want to store the ascii values in an nsarray it is going to be expensive. NSArray can only hold objects so you're going to have to create an NSNumber for each ASCII value:
unsigned len = [string length];
NSMutableArray arr = [NSMutableArray arrayWithCapacity:len];
for (unsigned i = 0; i < len; ++i) {
[arr addObject:[NSNumber numberWithUnsignedShort:[string characterAtIndex:i]]];
}
2) to go back to an NSString you'll need to use an MSMutableString and append each byte to the NSMutableString.
After saying that I'd suggest you don't use this method if you can avoid it.
A better approach would be to use #EmilioPelaez's answer. To go back from a memory buffer to an NSString is simple and inexpensive compared to iterating and concatting strings.
NSString * stringFromMemory = [[NSString alloc] initWithBytes:buffer length:len encoding: NSASCIIStringEncoding];
I ended up using the syntax I found here. Thanks for the help
How to convert ASCII value to a character in Objective-C?
NSString has a method to get the characters in an array:
NSString *string = "This is some string. It has spaces, punctuation, AND capitals.";
unichar *buffer = malloc(sizeof(unichar) * [string lenght]);
[string getCharacters:buffer range:NSMakeRange(0, [string length])];
If you check the definition of unichar, it's an unsigned short.
I know it must be a very simple thing to do but I've never had to treat strings before (in Objective-C) and apparently there's not RegEx on Cocoa-Touch.
Well, the situation is:
I have a text field to get a value (money, such as 32.10 for instance).
The problem:
If the user types in a symbol such as #, /, # etc. my app will crash.
The Question: How can I treat this string to remove the symbols if there are any?
you can try this:
NSString *s = #"12.827##584";
NSCharacterSet *removeCharSet = [NSCharacterSet characterSetWithCharactersInString:#"/:##"];
s = [[s componentsSeparatedByCharactersInSet: removeCharSet] componentsJoinedByString: #""];
NSLog(#"%#", s);
You do get regex in Cocoa Touch.
Here's a good discussion of the varying degrees of regex power in iOS, the blocks example at the end should get you most of the way there.
http://volonbolon.net/post/861427732/text-handling-in-ios-4
I understand you're trying to figure out the number included in the UITextFields's text property and assign it to a float variable.
Try using an NSScanner for this:
NSScanner* textScanner = [NSScanner localizedScannerWithString:textfield.text];
float* floatValue;
[textScanner scanFloat:&floatValue];
floatValue now contains the parsed float value of your textfield.
I'd like to create a regular expression that will match and return based on the following criteria:
1) I have N search terms entered by a user
2) I have a body of text.
3) I want to return a list of all the occurrences of all the search terms entered by the user plus surrounding context. I think (\w+\W+){,4}(", ")(\W+\w+){,4} might work.
4) I don't know how to use RegexKitLite at all. Do I invoke a RegexKitLite class? or does it interface into NSString somehow?
RegexKitLite defines a category on NSString. To get an array of substrings matching a pattern, use componentsMatchedByRegex:, as shown in the "Creating an Array of Every Match" section of the documentation.
NSArray *words = [NSArray arrayWithObjects:#"brown",#"lazy",nil];
NSString *pattern = [NSString stringWithFormat:#"(\\w+\\W+){0,4}(%#)(\\W+\\w+){0,4}",[words componentsJoinedByString:#"|"]];
NSString *text = #"the quick brown fox jumped over the lazy dog";
NSArray *matches = [text componentsMatchedByRegex:pattern];
I'm writing an NSString to a plist file but after its written to the plist, and when I try to open i get the following message
"This document "mylist.plist" could not be opened XML parser error: Unexpected character 2 at line 1 Old-style plist parser error: Unexpected';' or '=' after key at line 1"
Here is my code:
NSString *temp = [NSString stringWithFormat:#"%#\n Selection is %# \n %d for %.2lf = %.2lf", [NSDate date], #"IPC", 2, 42.34, 2 * 42.34];
[temp writeToFile:[self getPathName:#"mylist.plist"] atomically:YES];
any help would be appreciated.
Thanks,
-[NSString writeToFile...] does not create a plist. It creates a text file. There is no such thing as "writing a string to a plist". Only NSArray and NSDictionary objects can be written to plist files. Those can then contain NSString objects (and other objects, like NSDate and NSData, etc), but what you're asking for is not possible.
For more information, check out the Property List Programming Guide.
Edit: I should clarify what I mean by "creating a plist". When I say that, I'm referring to the XML documents defined by the Apple Plist DTD: http://www.apple.com/DTDs/PropertyList-1.0.dtd
%#\n Selection is %# \n %d for %.2lf = %.2lf is definitely not in any plist format. If you want to retain the plist format, use +[NSPropertyListSerialization dataFromPropertyList:...] to convert the string into data as a plist, then save the data.
And I don't see a reason to use plist if you're only storing 1 string. You can simply save as a .txt and load it using +[NSString stringWithContentsOfFile:...].