I want to check whether a string contains any of the substrings that I place in an array. Basically, I want to search the extensions of a file, and if the file is an "image", i want certain code to execute. The only way I can think of categorizing the file as an "Image" without downloading the file is through the substring in a string method. This is my code so far:
NSString *last5Chars = [folderName substringFromIndex: [folderName length] - 5];
NSRange textRangepdf;
textRangepdf =[last5Chars rangeOfString:#"pdf"];
if(textRangepdf.location != NSNotFound)
{
[self.itemType addObject:#"PDF.png"];
}
Is it possible to do this where I can check if last5Chars contains #"jpg" or #"gif" of #"png" etc...?? Thanks for helping!
NSString *fileName;
NSArray *imgExtArray; // put your file extensions in here
BOOL isImage = [imgExtArray containsObject:[fileName pathExtension]];
[folderName hasSuffix:#".jpg"] || [folderName hasSuffix:#".gif"]
obviously you can put it into a loop, if you have a whole arrayful.
Rather than mess about with ranges and suffixes, NSString has a method that treats an NSString as a path and returns an extension, it's called pathExtension.
Have a look in the NSString Documentation
Once you get the extension you can check it against whatever strings you want.
Related
I have a weird one for you guys today, I think my NSStrings are incorrectly encoded.
NSString * convertedString = [NSString stringWithUTF8String:mesh->groupMesh[i].materialData->textureName];
-textureName is just a c style string that I'm converting into an NSString.
-The string is: "dennum1.png"
NSArray * line = [convertedString componentsSeparatedByString:#"."];
NSString * texPath = [[NSBundle mainBundle] pathForResource:line[0] ofType:line[1]];
I then split it into an NSArray line, separated by periods "."
This makes it so that line[0] is dennum1, and line[1] is png.
I even do an NSLog to make sure:
NSLog(#"Name:%# Type:%#", line[0], line[1]);
2013-09-21 02:15:27.386 SteveZissou[8846:c07] Name:dennum1 Type:png
I parse this over to the pathForResource function and I get a (null) response.
BUT if I hard type the file name into the code I.E:
convertedString = #"dennum1.png";
NSArray * line = [convertedString componentsSeparatedByString:#"."];
NSString * texPath = [[NSBundle mainBundle] pathForResource:line[0] ofType:line[1]];
NSLog(#"This is the texPath: %#",texPath);
IT WORKS?!
This is the texPath: /Users/meow/Library/Application Support/iPhone Simulator/6.0/Applications/2DEB8076-5F9D-45DE-8A73-10B1C8A084B4/SteveZissou.app/dennum1.png
Is it possible that the NSString that I hard type in the code and the NSString that comes from the conversion are encoded differently?
When I NSLog them individually I get the same result regardless of type:
2013-09-21 02:15:27.386 SteveZissou[8846:c07] This is the c style string: dennum1.png
2013-09-21 02:15:27.386 SteveZissou[8846:c07] This is the converted c style string: dennum1.png
2013-09-21 02:15:27.386 SteveZissou[8846:c07] This is the string manually typed in: dennum1.png
What happens if you use the methods in NSPathUtilities that are designed to handle this stuff. Like:
NSString * texPath = [[NSBundle mainBundle] pathForResource:string.stringByDeletingPathExtension ofType:string.pathExtension];
Also, there's -fileSystemRepresentation which will convert an NSString to a const char * and throw an exception if the string can't be converted correctly.
I figured it out after HOURS of skimming through possible code combinations and found it by accident.
I used NSURL functions to get the path based on the strings I was using, which resulted in this path:
file://localhost/Users/meow/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/2DEB8076-5F9D-45DE-8A73-10B1C8A084B4/SteveZissou.app/dennum2.png%0D
Look at the very end! That's not supposed to be there! Turns out it's called a carriage return and it was pulled with the file (probably a remnant of the files formatting), but invisible to NSLog, however it wasn't invisible to NSURL (NSURL must read the bytes and display what they are?). So snipping the carriage return off the end of the path gave me the correct file and everything is OK.
I kept thinking to myself to use a hex editor to look at the file, but couldn't find one on the mac appstore free, I think if this was windows I would've caught it in half the time.
I wants to remove specific characters or group substring from NSString.
mean
NSString *str = #" hello I am #39;doing Parsing So $#39;I get many symbols in &my response";
I wants remove #39; and $#39; and & (Mostly these three strings comes in response)
output should be : hello I am doing Parsing So i get many symbols in my response
Side Question : I can't write & #39; without space here, because it converted in ' <-- this symbol. so i use $ in place of & in my question.
you should use [str stringByReplacingOccurrencesOfString:#"#39" withString:#""]
or you need replace strings of concrete format like "#number"?
try below code ,i think you got whatever you want simply change the charecterset,
NSString *string = #"hello I am #39;doing Parsing So $#39;I get many symbols in &my response";
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"#39;$&"];
NSString *result = [[string componentsSeparatedByCharactersInSet:trim] componentsJoinedByString:#""];
NSLog(#"%#", result);
I need to parse a URL in the following format:
http://www.example.com/?method=example.method&firstKey=firstValue&id=1893736&thirdKey=thirdValue
All I need is the value of 1893736 within &id=1893736.
I need to do the parsing in Objective-C for my iPhone project. I understand it must have something to do with regular expression. But I just have no clue how to do it.
Any suggestions would be appreciated. :)
You don't need a regex for this. You can try something like this
NSString *url = #"http://www.example.com/?method=example.method&firstKey=firstValue&id=1893736&thirdKey=thirdValue";
NSString *identifier = nil;
for (NSString *arg in [[[url pathComponents] lastObject] componentsSeparatedByString:#"&"]) {
if ([arg hasPrefix:#"id="]) {
identifier = [arg stringByReplacingOccurrencesOfString:#"id=" withString:#""];
}
}
NSLog(#"%#", identifier);
Don't use regular expressions. Use NSURL to reliably extract the query string and then use this answer's code to parse the query string.
Use this:
.*/\?(?:\w*=[^&]*&)*?(?:id=([^&]*))(?:&\w*=[^&]*)*
And grap first group: \1. You will obtain 1893736.
Simplifying
If the id can consist of only digits:
.*/\?(?:\w*=[^&]*&)*?(?:id=(\d*))(?:&\w*=[^&]*)*
If you don't care about capturing uninterested groups (use \3 or id in this case):
.*/\?(\w*=.*?&)*?(id=(?<id>\d*))(&\w*=.*)*
More simpler version (use \3):
.*/\?(.*?=.*?&)*(id=(\d*))(&.*?=.*)*
Instead of using regex, you can split the string representation of your NSURL instance. In your case, you can split the string by the appersand (&), loop the array looking for the prefix (id=), and get the substring from the index 2 (which is where the = ends).
I need to display subscripts and superscripts (only arabic numerals) within a UILabel. The data is taken from an XML file. Here is the snippet of XML file:
<text><![CDATA[Hello World X\u00B2 World Hello]]></text>
Its supposed to display X2 (2 as superscript). When I read the string from the NSXMLParser and display it in the UILabel, it displays it as X\u00B2. Any ideas on how to make it work?
I think you can do something like this, assuming the CDATA contents have been read into an NSString and passed into this function:
-(NSString *)removeUnicodeEscapes:(NSString *)stringWithUnicodeEscapes {
unichar codeValue;
NSMutableString *result = [stringWithUnicodeEscapes mutableCopy];
NSRange unicodeLocation = [result rangeOfString:#"\\u"];
while (unicodeLocation.location != NSNotFound) {
// Get the 4-character hex code
NSRange charCodeRange = NSMakeRange(unicodeLocation.location + 2, 4);
NSString *charCode = [result substringWithRange:charCodeRange];
[[NSScanner scannerWithString:charCode] scanHexInt:&codeValue];
// Convert it to an NSString and replace in original string
NSString *unicodeChar = [NSString stringWithFormat:%C", codeValue];
NSRange replacementRange = NSMakeRange(unicodeLocation.location, 6);
[result replaceCharactersInRange:replacementRange withString:unicodeChar];
unicodeLocation = [result rangeOfString:#"\\u"];
}
return result;
}
I haven't had a chance to try this out, but I think the basic approach would work
\u00B2 is not any sort of XML encoding for characters. Apparently your data source has defined their own encoding scheme (which, frankly, is pretty stupid as XML is capable of encoding these directly, using entities outside of CDATA blocks).
In any case, you'll have to write your own parser that handles \u#### and converts that to the correct character.
I asked the question to my colleague and he gave me a nice and simple workaround. Am describing it here, in case others also get stuck at this.
Firstly goto this link. It has a list of all subscripts and superscripts. For example, in my case, I clicked on "superscript 0". In the following HTML page detailing "superscript 0", goto "Java Data" section and copy the "⁰". You can either place this directly in XML or write a simple regex in obj-c to replace \u00B2 with "⁰". And you will get nice X⁰. Do the same fro anyother superscript or subscript that you might want to display.
I am trying to write a program that creates dynamically named .csv files that need to be either retrieved or deleted at a later run date. What I am trying to do is this:
I would like to run an algorithm that will find out if any of these types of files exist. For example, if I dynamically name the file something like foobar##.csv with the ## indicating a number being dynamically being generated and appended to the filename, I would like to find if any foobar##.csv file exists regardless of the number used. Normally I would use a line of code like this:
NSString *dataFileName = [[self documentPath] stringByAppendingPathComponent:#"foobar01.csv"];
Right now I just use a loop that cycles through each value and trips a bool if one is found, but I know this isn't a best practice as it limits the possible filename numbers the user can use. Any insight into how I could use some sort of wildcard on a search like this would be appreciated.
Also, I would want to create a method that would delete any .csv files the program finds, but I'm assuming that the method used to solve the above algorithm can be used for the deletion one as well.
Wildcard match
To match using a wildcard string the query can use like instead of the comparison operator and include the “*” (match zero or more characters) or “?” (match exactly 1 character) as wildcards as follows:
NSString *match = #"imagexyz*.png";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF like %#", match];
NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
http://useyourloaf.com/blog/2010/7/27/filtering-arrays-with-nspredicate.html
Take a look at NSFileManagers contentsOfDirectoryAtPath:error: method. It will return an array with strings containing the names of all objects (files and directories) of the directory in question.
You could then enumerate through that array and check for occurances of "foobar" in those strings. Either do something to the files you found right away or store the "positive" filenames in another array for later processing.
sample code for what the other poster said more or less.
+(NSMutableArray*) allocLocalFiles
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error = nil;
NSArray *origContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory
error:&error];
NSMutableArray * files = [[NSMutableArray alloc]init];
for (NSString* file in origContents) {
NSString * ext = [file pathExtension];
if ([ext compare:#"csv"]==0 && something_else)
{
[files addObject:
[NSString stringWithFormat:#"%#/%#",documentsDirectory,file]];
}
}
return files;
}