appending string- works with string with one word but not two - objective-c

I'm appending a string to a url which then inputs into a database, it works with a single worded string e.g
NSString * string = #"one";
however if my string has two words such as
NSString * string = #"one two";
it does not work. Please see the code below.
NSMutableString * urlString = [NSMutableString stringWithString:url];
[urlString appendString:[NSString stringWithFormat:#"?%#=%#",kWord,word]];
The problem obviously lies with stringWithFormat;
turns out the problem is with the space.

Space characters (and certain others) are not allowed in URLs. You need to convert the space to %20. Here is the proper solution:
NSString *url = #"http://example.com/process.php";
NSString *kword = #"param";
NSString *word = #"one two";
NSMutableString * urlString = [url mutableCopy];
[urlString appendFormat:#"?%#=%#", kWord, [word stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

I have tried couple exampes here, hope it helps.
NSString *string1 = #"String1";
NSString *string2 = #"String2 String3";
NSMutableString *appendingString=[NSMutableString stringWithString: [string1 stringByAppendingString:string2]];
NSLog(#"String1:%# String2:%#",string1,string2);
NSLog(#"StringwithAppend:%#",appendingString);
//------
NSString *url=#"www.abc.com";
NSMutableString * urlString = [NSMutableString stringWithString:url];
NSLog(#"URL String before append:%#",urlString);
NSString *kWord=#"key";
NSString *word=#"word";
[urlString appendString:[NSString stringWithFormat:#"?%#=%#",kWord,word]];
NSLog(#"URL String after append:%#",urlString);
Console Log:
String1:String1 String2:String2 String3
StringwithAppend:String1String2 String3
URL String before append:www.abc.com
URL String after append:www.abc.com?key=word

Try it this way.
NSString * urlString= [NSString stringWithFormat:#"%#?%#=%#", url, kword, word];

Related

How to remove the first space from the NSString?

I want to remove only first space in below string.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after
GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString: to locate the first space, then use stringByReplacingCharactersInRange:withString: to replace it with the empty string.
Remove space by using below code.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:#"IF_Distance " withString:#"IF_Distance"];
Try This:
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:#"%# ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output:
str = #"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString: and then remove by using stringByReplacingCharactersInRange:withString: method.
Like,
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = #" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:#""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:#" "]];
}

Objective-C Split a String and get last item

I have a string like so:
NSString *path = #"\\fake\aaa\bbb\ccc\ddd\eee.pdf";
and I split the string into an array like so:
NSArray *array = [path componentsSeparatedByString:#"\"];
Now there are two things I need here.
I need a string with everything except eee.pdf
I need the last item in the array as a string (eee.pdf)
How would I do this?
Just for fun, there is a little-known way to get an NSURL with its benefit from a windows file path
NSString *path = #"\\\\fake\\aaa\\bbb\\ccc\\ddd\\eee.pdf";
NSURL *url = CFBridgingRelease(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)path, kCFURLWindowsPathStyle, false));
NSString *fileName = url.lastPathComponent;
NSString *parentDirectory = url.URLByDeletingLastPathComponent.path;
Finally you have to convert parentDirectory back to windows path style (backslashes).
But if you mean POSIX paths used in OS X, it's much easier
NSString *path = #"/fake/aaa/bbb/ccc/ddd/eee.pdf";
NSURL *url = [NSURL fileURLWithPath:path];
NSString *fileName = url.lastPathComponent;
NSString *parentDirectory = url.URLByDeletingLastPathComponent.path;
I think you're trying to get the filepath and filename from a full path. There are better ways of doing that. But since you simply asked for the question, here's my answer. Please note that this is not the best approach. In addition, you have to escape the backslashes by using a preceding backslash.
NSString *path = #"\\fake\\aaa\\bbb\\ccc\\ddd\\eee.pdf";
NSArray *array = [path componentsSeparatedByString:#"\\"];
NSMutableArray *removedArray = [[NSMutableArray alloc] init];
for(int i=0; i< array.count -1; i++){
[removedArray addObject:[array objectAtIndex:i]];
}
NSString *joinedString =[removedArray componentsJoinedByString:#"\\"];
NSString *fileName = [array lastObject];
NSLog(#"Path: %#", joinedString);
NSLog(#"Filename: %#", fileName);
For the last element use the lastObject property of the NSArray.
For a string without the last element use subarrayWithRange: using array.count-1 for the NSRange length.
Then join the remaining array with componentsJoinedByString:.
NSString *fileName = [array lastObject];
NSArray *newArray = [array subarrayWithRange:NSMakeRange(0, array.count-1)];
NSString *directoryPath = [newArray componentsJoinedByString:#"\\"];

Trim NSString to specific pathComponent [duplicate]

This question already has answers here:
How to take NSString after specific character which occurs multiple time in NSString?
(3 answers)
Closed 8 years ago.
I have an NSString which represents paths like
.../App/Some/Directory/myClass.mm
Now I want to trim
.../App/Some/Directory/
to get only the Class' name/file. How to achieve this?
You can convert your string to a NSURL, and the get the lastPathComponent to get the "myClass.mm" you want.
NSString* filePath = #"/App/Some/Directory/myClass.mm";
NSURL *url = [NSURL URLWithString:filePath];
NSString* lastComponent = [url lastPathComponent];
Should do the trick.
You can separate the string into components (using the / as the separator), and then the filename will be the last element of the output array.
NSString *input = #".../App/Some/Directory/myClass.mm";
NSArray *array = [input componentsSeparatedByString:#"/"];
NSLog( #"%#", [array lastObject] );
NSString class has lastPathComponent method, also you can solve your problem like this:
NSString *path;
NSString *trimmed;
NSRange range = [path rangeOfString:#"/" options:NSBackwardsSearch];
if (range.location != NSNotFound)
trimmed = [path substringFromIndex:range.location+1];
else
trimmed = path;
NSString* str = #"/App/Some/Directory/myClass.mm";
NSRange replaceRange = [str rangeOfString:#"/myClass.mm"];
if (replaceRange.location != NSNotFound){
NSString* result = [str stringByReplacingCharactersInRange:replaceRange withString:#""];
NSLog(#"Result :%#",result);
}

Inject a character while concatenating with stringByAppendingString

Is there a way to concatenate two strings and inject a character. I have :
NSString *firstString = #"http://www.stackoverflow.com";
NSString *secondString = #"supercooloptions";
NSString *result = [firstString stringByAppendingString: secondString];
NSLog(#"the final string with "/" injection = %#", result);
I'd like the final string with "/" injected = www.stackoverflow.com/supercooloptions
You can use a different method - for example, stringWithFormat:
NSString *result = [NSString stringWithFormat:#"%#/%#", firstString, secondString];
For this specific case, use stringByAppendingPathComponent:
NSString *result = [firstString stringByAppendingPathComponent:secondString];

Objective-C: Substring and replace

I have a NSString which is a URL. This URL need to be cut:
NSString *myURL = #"http://www.test.com/folder/testfolder";
NSString *test = [myURL stringByReplacingCharactersInRange:[myURL rangeOfString:#"/" options:NSBackwardsSearch] withString:#""];
I have this URL http://www.test.com/folder/testfolder and I want that the test variable should have the value http://www.test.com/folder/, so the testfolder should be cut.
So I tried to find the NSRange testfolder to replace it with an empty string.
But it does not work. What I am doing wrong?
You can turn it into a URL and use -[NSURL URLByDeletingLastPathComponent]:
NSString *myURLString = #"http://www.test.com/folder/testfolder";
NSURL *myURL = [NSURL URLWithString:myURLString];
myURL = [myURL URLByDeletingLastPathComponent];
myURLString = [myURL absoluteString];
Try this:
NSString *myURL = #"http://www.test.com/folder/testfolder";
NSString *test = [myURL stringByDeletingLastPathComponent];
NSLog(#"%#", test);
you should get > http://www.test.com/folder/
You can't use the NSRange returned by [myURL rangeOfString:#"/" options:NSBackwardsSearch] because its length is "1". So to keep with your idea to use NSRange (other replies using stringByDeletingLastPathComponent seems to be very valid too), here is how you could do it :
NSRange *range=[myURL rangeOfString:#"/" options:NSBackwardsSearch];
NSString *test = [myURL stringByReplacingCharactersInRange:NSMakeRange(range.location,test.length-range.location) withString:#""];