how to replace one substring with another in Objective C? - objective-c

I want to replace an NSString substring with another substring in Objective C.
I know how to locate the substring I want to replace:
NSRange range = [string rangeOfString:substringIWantToReplace];
NSString *substring = [string substringFromIndex:NSMaxRange(range)];
But when it comes to actually removing/replacing it, I'm a little confused. Do I follow the C++ method at Replace substring with another substring C++? Or the C method at how to replace substring in c?? There's a related question at Objective-C: Substring and replace, but the string in question is a URL, so I don't think I can use the answers.

I think your answer is here Replace occurrences of NSString - iPhone:
[response stringByReplacingOccurrencesOfString:#"aaa" withString:#"bbb"]; defenetly works on any string and URL also.
If your concern about percent-notation of url and you want to be sure it will be replaced properly, you can firstly decode string, replace, and then encode:
// decode
NSString *path = [[#"path+with+spaces"
stringByReplacingOccurrencesOfString:#"+" withString:#" "]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// replace
path = [path stringByReplacingOccurrencesOfString:#"aaa" withString:#"bbb"]
// encode
path = CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)path,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8 );

This is how I check for a substring and replace/remove substrings from NSString:
if([titleName rangeOfString:#"""].location != NSNotFound) {
titleName = [titleName stringByReplacingOccurrencesOfString:#""" withString:#"\""];
}

Related

Regular expression to validate a URL safe string in Objective C

In my iPhone application I am constructing a URL by passing some params
as in
NSURL * url;
url = [url URLByAppendingPathComponent:Param1];
Now I want to validate Param1 to accept only the URL safe characters, other way around is to encode the URL I agree , but I need to validate the Param1 since it is exposed to the user to change, is there any stright forward native API to do so?, or Regex is the only way? please provide me the Regex if so , Thanx in advance
You could encode it
NSString *encodedString = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)originalString,
NULL,
CFSTR(":/?#[]#!$&'()*+,;="),
kCFStringEncodingUTF8);
if (![encodedString isEqualToString:originalString]) {
// It contains characters that are probably not legal.
}
Or you could just check for the characters listed above, but what fun would that be? :-)
NSCharacterSet *charSet = [NSCharacterSet
characterSetWithCharactersInString:
#":/?#[]#!$&'()*+,;="];
NSRange range = [string rangeOfCharacterFromSet:charSet];
if (range.location != NSNotFound) { ... }

Objective C remove end of string after certain character [duplicate]

This question already has answers here:
Remove Characters and Everything After from String
(2 answers)
Closed 8 years ago.
I can't seem to find the answer to this anywhere. I can do it in c but objective c is difficult.
I want to cut the end of a string after a certain character
so user#example.com will become user (cut at '#')
How do I do this?
This will give you the first chunk of text that comes before your special character.
NSString *separatorString = #"#";
NSString *myString = #"user#example.com";
NSString *myNewString = [myString componentsSeparatedByString:separatorString].firstObject;
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
You can use a combination of substringToIndex: and rangeOfString: methods, like this:
NSString *str = #"user#example.com";
NSRange pos = [str rangeOfString:#"#"];
if (pos.location != NSNotFound) {
NSString *prefix = [str substringToIndex:pos.location];
}
Notes:
You need to check the location against NSNotFound to ensure that the position is valid.
substringToIndex: excludes the index itself, so the # character would not be included.

stringByAddingPercentEscapesUsingEncoding does not escape "&"

I am using stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding to pass data to a php script. The problem is if the field has the char '&' in the text lets say: 'someone & cars', only the text "someone" is saved, everything after the '&' doesn't.
To create the string I use [NSString stringWithFormat:], so I have like 5 field in the form and if I use stringbyReplacingOcorrencesOfstring:#"&", what it does is replace the whole string not only the char '&' from the text field, so I get error.
Any ideas?
Unfortunately, stringByAddingPercentEscapesUsingEncoding: doesn't actually escape all necessary URL characters.
Instead, you can use the lower-level CoreFoundation function:
(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)myString, NULL, (CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding));
or, when using ARC:
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)myString, NULL, (__bridge CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)));
See this post for an example of a category on NSString that uses this function.
Following works using stringByAddingPercentEncodingWithAllowedCharacters if you want to specifically allow what would be encoded yourself. I'm using after base64 so this works fine.
NSString *charactersToEscape = #"!*'();:#&=+$,/?%#[]\" ";
NSCharacterSet *customEncodingSet = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *url = [NSString stringWithFormat:#"%#", #"http://www.test.com/more/test.html?name=john&age=28"];
NSString *encodedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:customEncodingSet];

Replacing one character in a string in Objective-C

Hoping somebody can help me out - I would like to replace a certain character in a string and am wondering what is the best way to do this?
I know the location of the character, so for example, if I want to change the 3rd character in a string from A to B - how would I code that?
If it is always the same character you can use:
stringByReplacingOccurrencesOfString:withString:
If it is the same string in the same location you can use:
stringByReplacingOccurrencesOfString:withString:options:range:
If is just a specific location you can use:
stringByReplacingCharactersInRange:withString:
Documentation here:
https://developer.apple.com/documentation/foundation/nsstring
So for example:
NSString *someText = #"Goat";
NSRange range = NSMakeRange(0,1);
NSString *newText = [someText stringByReplacingCharactersInRange:range withString:#"B"];
newText would equal "Boat"
NSString *str = #"123*abc";
str = [str stringByReplacingOccurrencesOfString:#"*" withString:#""];
//str now 123abc
Here is the code:
[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:#"B"];
Use the replaceCharactersInRange: withString: message on a NSMutableString object.

How to check if NSString begins with a certain character

How do you check if an NSString begins with a certain character (the character *).
The * is an indicator for the type of the cell, so I need the contents of this NSString without the *, but need to know if the * exists.
You can use the -hasPrefix: method of NSString:
Objective-C:
NSString* output = nil;
if([string hasPrefix:#"*"]) {
output = [string substringFromIndex:1];
}
Swift:
var output:String?
if string.hasPrefix("*") {
output = string.substringFromIndex(string.startIndex.advancedBy(1))
}
You can use:
NSString *newString;
if ( [[myString characterAtIndex:0] isEqualToString:#"*"] ) {
newString = [myString substringFromIndex:1];
}
hasPrefix works especially well.
for example if you were looking for a http url in a NSString, you would use componentsSeparatedByString to create an NSArray and the iterate the array using hasPrefix to find the elements that begin with http.
NSArray *allStringsArray =
[myStringThatHasHttpUrls componentsSeparatedByString:#" "]
for (id myArrayElement in allStringsArray) {
NSString *theString = [myArrayElement description];
if ([theString hasPrefix:#"http"]) {
NSLog(#"The URL is %#", [myArrayElement description]);
}
}
hasPrefix returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.
- (BOOL)hasPrefix:(NSString *)aString,
parameter aString is a string that you are looking for
Return Value is YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.
As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.
NSString* myString = #"10:Username taken";
if([myString hasPrefix:#"10"]) {
//display more elegant error message
}
Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.
NSString *stringWithoutAsterisk(NSString *string) {
NSRange asterisk = [string rangeOfString:#"*"];
return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}
Another approach to do it..
May it help someone...
if ([[temp substringToIndex:4] isEqualToString:#"http"]) {
//starts with http
}
This might help? :)
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/characterAtIndex:
Just search for the character at index 0 and compare it against the value you're looking for!
This nice little bit of code I found by chance, and I have yet to see it suggested on Stack. It only works if the characters you want to remove or alter exist, which is convenient in many scenarios. If the character/s does not exist, it won't alter your NSString:
NSString = [yourString stringByReplacingOccurrencesOfString:#"YOUR CHARACTERS YOU WANT TO REMOVE" withString:#"CAN either be EMPTY or WITH TEXT REPLACEMENT"];
This is how I use it:
//declare what to look for
NSString * suffixTorRemove = #"</p>";
NSString * prefixToRemove = #"<p>";
NSString * randomCharacter = #"</strong>";
NSString * moreRandom = #"<strong>";
NSString * makeAndSign = #"&amp;";
//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:#"&"];
//check the output
NSLog(#"returnStr IS NOW: %#", returnStr);
This one line is super easy to perform three actions in one:
Checks your string for the character/s you do not want
Can replaces them with whatever you like
Does not affect surrounding code
NSString* expectedString = nil;
if([givenString hasPrefix:#"*"])
{
expectedString = [givenString substringFromIndex:1];
}