Below I pass a programming question: Calculate the code line number of the file, summarize the use method of NSString, Nsarray.
#import <Foundation/Foundation.h>
/*
Path: The full path of the file (may be a folder, or it may be a file)
return value int: line of code
*/
Nsuintegercodelinecount (NSString *path)
{
1. Get the File Manager
Nsfilemanager *mgr = [Nsfilemanagerdefaultmanager];
2. Whether the tag is a folder
BOOL dir = NO; Whether the tag is a folder
Mark if this path exists
BOOL exist = [Mgrfileexistsatpath:path isdirectory:&dir];
3. If not present, return directly to 0
if (!exist)
{
NSLog (@ "file path does not exist!) ");
return 0;
}
The code can come and show that the path exists
if (dir)
{//Folder
Get all contents (folders, files) under the current folder path
Nsarray *array = [Mgrcontentsofdirectoryatpath:path Error:nil];
Define a variable to hold the total number of all files in the path
int count = 0;
Iterate through the names of all the sub-Files (folders) in the array
For (nsstring *filenamein Array)
{
Get the full path of the sub-file (clip)
NSString *fullpath = [nsstringstringwithformat:@ "%@/%@", path, filename];
Accumulate total rows per sub-path
Count + = Codelinecount (FullPath);
}
return count;
}
Else
{//File
Determine the extension name of the file (ignoring case)
NSString *extension = [[Pathpathextension] lowercasestring];
if (![ extensionisequaltostring:@ "H"]
&&! [extensionisequaltostring:@ "M"]
&&! [extensionisequaltostring:@ "C"])
{
The file extension is not H, and it's not m, and it's not C.
return 0;
}
Loading file contents
NSString *content = [Nsstringstringwithcontentsoffile:path encoding:nsutf8stringencoding error:nil];
Cut the contents of the file into each row
Nsarray *array = [contentcomponentsseparatedbystring:@ "\ n"];
Remove the/users/apple/desktop/ios exercise in front of the file path
Nsrange range = [path rangeofstring:@ "/users/apple/desktop/ios exercise"];
NSString *str = [path stringbyreplacingcharactersinrange:rangewithstring:@ "];
Print file path and number of lines
NSLog (@ "%@-%ld", str, array.count);
return array.count;
}
}
int main ()
{
Nsuinteger count = Codelinecount (@ "/users/apple/desktop/ios XI");
NSLog (@ "%ld", count);
return 0;
}
void Test ()
{
NSString *str = @ "Jack\nrose\njim\njake";
[Str writetofile:@ "/users/apple/desktop/abc.txt" atomically:YESencoding:NSUTF8StringEncoding Error:nil];
Nsarray *array = [str componentsseparatedbystring:@ "\ n"];
For (NSString *line in array)
{
NSLog (@ "%@", line);
}
int count =codelinecount (@ "/users/apple/desktop/ios Exercise/Code/FOUNDATION/MAIN.M");
NSLog (@ "count=%d", count);
}
Dark Horse programmer-ios notes-foundation nsstring, Nsarray