How to replace whitespaces by a plus "+" sign - objective-c

hey all i want a code the replace whitespaces by a + sign in objective-c

In case you are asking this because you need to encode URLs, use this
NSString* escapedUrlString =
[unescapedString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
If you just need space to +, use
[str stringByReplacingOccurrencesOfString:#" " withString:#"+"];

return [thatString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
If your real target is to escape URL component, use the -stringByAddingPercentEscapesUsingEncoding: method instead.

Related

Removing the front character from NSMutableString

I am trying to remove the front character of a NSMutableString and have tried:
[str setString: [str substringFromIndex:1]] ,
[str deleteCharactersInRange:NSMakeRange(0,1)]
and a few others. These two either remove every character or every character except for the one I am trying to remove so for example if I have the String "-2357" and am trying to remove the "-" then I get just the "-" when I should get "2357".
Am I doing something wrong, and how can I fix this?
If you want to use the deleteCharactersInRange method, do this
NSRange range = {0,1};
[str deleteCharactersInRange:range];
Or, you could use substringFromIndex like so:
str = [str substringFromIndex:1];
Contrary to what you are saying, [str deleteCharactersInRange:NSMakeRange(0,1)] should work fine, I don't know why that is not working.
[str substringToIndex:1] will return the string from the beginning to the index 1, which is -. What you want is substringFromIndex. And as this method returns a NSString, you will need to assign it to str; just calling the method on str is not enough.
Edit
Using the deleteCharactersInRange may pose problems for some type of characters. For more information refer to this a question here.
Instead, you can safely use
[str deleteCharactersInRange:[str rangeOfComposedCharacterSequenceAtIndex:0]]
instead of:
[str substringToIndex:1]
Do this:
[str substringFromIndex:1]
If you want to remove first character of the string you can use this:-
string = [string substringFromIndex:1];

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];

Objective-C – Replace newline sequences with one space

How can I replace newline (\n) sequences with one space.
I.e the user has entered a double newline ("\n\n") I want that replaced with one space (" "). Or the user has entered triple newlines ("\n\n\n") I want that replaced with also one space (" ").
Try this:
NSArray *split = [orig componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
split = [split filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"]];
NSString *res = [split componentsJoinedByString:#" "];
This is how it works:
First line splits by newline characters
Second line removes empty items inserted for multiple separators in a row
Third line joins the strings back using a single space as the new separator
3 times more performant than using componentsSeparatedByCharactersInSet
NSString *fixed = [original stringByReplacingOccurrencesOfString:#"\\n+"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, original.length)];
Possible alternative regex patterns:
Replace only space: [ ]+
Replace space and tabs: [ \\t]+
Replace space, tabs and newlines: \\s+
Replace newlines: \\n+
As wattson says you can do this with NSRegularExpression but the code is quite verbose so if you want to do this at several places I suggestion you to do a helper method or even a NSString category with method like -[NSString stringByReplacingMatchingPattern:withString:] or something similar.
NSString *string = #"a\n\na";
NSLog(#"%#", [[NSRegularExpression regularExpressionWithPattern:#"\\n+"
options:0
error:NULL]
stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#" "]);
Use a regular expression, something like "s/\n+/\w/" (a replace which will match 1 or more newline character and replace with a single white space)
this question has a link to a regex library, but there is NSRegularExpression available too

How do I remove '\' characters from my NSString

/images/content/booking_thumbs_uk/s_kl/50000/THB_999_H54007.jpg
changes to:
/images/content/booking_thumbs_uk/s_kl/00000/THB_999_H2470.jpg
NSString* original=#"\\/images\\/content\\/booking_thumbs_uk\\/s_kl\\/50000\\/THB_999_H54007.jpg";
NSString* removed=[original stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSLog(#"%#",removed); // shows /images/content/booking_thumbs_uk/s_kl/00000/THB_999_H2470.jpg
Be very careful, because inside the source code between "..." the backslash has a special meaning. In order to represent an honest backslash, you need to double it, like "\\".
You can use newString = [oldString stringByReplacingOccurrencesOfString:#"\\" withString:#""];

How to remove first 3 characters from NSString?

I have a string like this "A. rahul VyAs"
and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"
How do i achieve this?
You can use the NSString instance methods substringWithRange: or substringFromIndex:
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)];
or
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringFromIndex:3];
This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?
NSString * name = #"A. rahul VyAs";
NSString * prefixToRemove = #"A. ";
name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.
If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.
If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.
If you want to remove or change certain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.
Try this,
char *string=[#"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];
It's this simple:
myString = [myString subStringFromIndex:3]
That's it.