nsstring replace string in range - iphone

I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;
// Determine "{" location
NSRange startRange = [string rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [string length] - endRange.location;
endRange = [string rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
result = [string substringWithRange:startRange];
}
}
Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.

Try this one:
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
//NSString *result = nil;
// Determine "{" location
NSArray *array=[string componentsSeparatedByString:#"{"];
for(NSString *str in array){
NSString *newString=[[str componentsSeparatedByString:#"}"] objectAtIndex:0];
NSLog(#"%#",newString);
}

try this :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSMutableString *result = [[NSMutableString alloc] init];
NSArray *tempArray = [[string componentsSeparatedByString:#" "] mutableCopy];
for (int i=0; i < [tempArray count]; i++)
{
NSString *tempStr = [tempArray objectAtIndex:i];
NSRange startRange = [tempStr rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [tempStr length] - endRange.location;
endRange = [tempStr rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
//result = [tempStr substringWithRange:startRange];
[result appendString:[NSString stringWithFormat:#"%# ",[tempStr substringWithRange:startRange]]];
NSLog(#"%# ",result);
}
}
}
Take care for release for tempArray and result

I happen to have this code lying around. I think it does exactly what you want. I implemented it as a category on NSString. You use it like this:
NSString *template = #"{Hello} ({World}) ({How}) etc etc";
NSDictionary *vars = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bonjour", #"Hello",
#"Planet Earth", #"World",
#"Como", #"How",
// etc.
nil];
NSString *expandedString = [template stringByExpandingTemplateWithVariables:vars];
// expandedString is #"Bonjour (Planet Earth) (Como) etc etc"
Here's the code.
File NSString+TemplateExpansion.h
#import <Foundation/Foundation.h>
#interface NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary;
#end
File NSString+TemplateExpansion.m
#import "NSString+TemplateExpansion.h"
#implementation NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary
{
NSUInteger myLength = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:myLength];
NSRange remainingRange = NSMakeRange(0, myLength);
while (remainingRange.length > 0) {
NSRange leftBraceRange = [self rangeOfString:#"{" options:0 range:remainingRange];
if (leftBraceRange.location == NSNotFound)
break;
NSRange afterLeftBraceRange = NSMakeRange(NSMaxRange(leftBraceRange), myLength - NSMaxRange(leftBraceRange));
NSRange rightBraceRange = [self rangeOfString:#"}" options:0 range:afterLeftBraceRange];
if (rightBraceRange.location == NSNotFound)
break;
NSRange beforeLeftBraceRange = NSMakeRange(remainingRange.location, leftBraceRange.location - remainingRange.location);
[result appendString:[self substringWithRange:beforeLeftBraceRange]];
remainingRange = NSMakeRange(NSMaxRange(rightBraceRange), myLength - NSMaxRange(rightBraceRange));
NSRange keyRange = NSMakeRange(NSMaxRange(leftBraceRange), rightBraceRange.location - NSMaxRange(leftBraceRange));
NSString *key = [self substringWithRange:keyRange];
NSString *value = [dictionary objectForKey:key];
if (value)
[result appendString:value];
}
[result appendString:[self substringWithRange:remainingRange]];
return result;
}
#end

Related

ios - How to declare URLDecode?

I'm trying to get access token,when I decode URL it's getting an error,I think am declaring wrong here.How to declare URLDecode to get access token?
in .h file
#interface NSString (URLDecode)
-(NSString *)URLDecode;
#end
in .m file
-(NSString *)URLDecode
{
NSString *result = [(NSString*)self stringByReplacingOccurrencesOfString:#"+" withString:#" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
- (NSDictionary*)parsePairs:(NSString*)urlStr
{
NSRange r = [urlStr rangeOfString:#"="];
if(r.length == 0)
{
return nil;
}
//Here I'm getting an error
NSString* token = [[urlStr substringFromIndex:r.location + 1 ] URLDecode];
NSCharacterSet* objectMarkers;
objectMarkers = [NSCharacterSet characterSetWithCharactersInString:#"{}"];
token = [token stringByTrimmingCharactersInSet:objectMarkers];
NSError* regexError;
NSMutableDictionary* pairs = [NSMutableDictionary dictionaryWithCapacity:10];
NSRegularExpression* regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\"([^\"]*)\":\"([^\"]*)\""
options:0
error:&regexError];
NSArray* matches = [regex matchesInString:token
options:0
range:NSMakeRange(0, token.length)];
for(NSTextCheckingResult* result in matches)
{
for(int n = 1; n < [result numberOfRanges]; n += 2)
{
NSRange r = [result rangeAtIndex:n];
if(r.length > 0)
{
NSString* name = [token substringWithRange:r];
r = [result rangeAtIndex:n + 1];
if(r.length > 0)
{
NSString* value = [token substringWithRange:r];
[pairs setObject:value forKey:name];
}
}
}
}
regex = [NSRegularExpression regularExpressionWithPattern:#"\"([^\"]*)\":([0-9]*)"
options:0
error:&regexError];
matches = [regex matchesInString:token
options:0
range:NSMakeRange(0, token.length)];
for(NSTextCheckingResult* result in matches)
{
for(int n = 1; n < [result numberOfRanges]; n += 2)
{
NSRange r = [result rangeAtIndex:n];
if(r.length > 0)
{
NSString* name = [token substringWithRange:r];
r = [result rangeAtIndex:n + 1];
if(r.length > 0)
{
NSString* value = [token substringWithRange:r];
NSNumber* number = [NSNumber numberWithInt:[value intValue]];
[pairs setObject:number forKey:name];
}
}
}
}
return pairs;
}
Any ideas?
You need to make a cetgory of NSString in your Xcode project as :
1.
Then do as :
Then when you click Next button a cetgory will be created of NSString . Then use add code in that. And then Import this category in your class as :
#import "NSString+URLDecode.h"
and then call method declared in category over NSString as
NSString *decodedUrlStr = [urlStr URLDecode];
Hope it helps you.

Separate words from a NSString which are preceded by a hashtag

I have a NSString, for example:
"Had a #great time at the #party last night."
I want to separate this into an array, as so:
"Had a "
"#great"
" time at the "
"#party"
" last night."
How could i do this?
NSString *str = #"Had a #great time at the #party last night.";
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSArray *array = [str componentsSeparatedByString:#"#"];
NSMutableString *retStr= [[NSMutableString alloc] initWithString:[array objectAtIndex:0]];
[arr addObject:retStr];
for(int i=1 ; i<[array count];i++)
{
NSArray *array1 = [[array objectAtIndex:i] componentsSeparatedByString:#" "];
{
NSMutableString *retStr= [[NSMutableString alloc]init];
for (int i = 0;i< [array1 count]; i++)
{
if(i==0)
{
[retStr appendFormat:#" #%# ",[array1 objectAtIndex:i]];
[arr addObject:retStr];
retStr= [[NSMutableString alloc]init];
}
else
{
[retStr appendFormat:#"%# ",[array1 objectAtIndex:i]];
}
}
[arr addObject:retStr];
}
}
NSLog(#"%#",arr);
You will get the corect output as you want
try like this it'l helps you,
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#" "];
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF contains '#'"];
NSArray *b = [arr filteredArrayUsingPredicate:p];
NSLog(#"%#",b);
above predicate will returns the words which are not containg '#' symbol
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF like '#*'"];
it'l returns the words which are not started with the letter '#'
O/P:-
(
how,
are
)
EDIT:-
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#"#"];
NSMutableArray *result=[[NSMutableArray alloc]initWithObjects:[arr objectAtIndex:0], nil];
for(int i=1;i<[arr count];i++){
[result addObject:[NSString stringWithFormat:#"#%#",[arr objectAtIndex:i]]];
}
NSLog(#"%#",result);
O/P:-
(
"how are ",
"#you ",
"#friend"
)
Try to use this regexp: (#.+?\\b)|(.+?(?=#|$))
It find words which begins with hashtag and subsequences which ends with hashtag
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((#.+?\\b)|(.+?(?=#|$)))"
options:0
error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult* match in matches ) {
NSLog(#"%#", [string substringWithRange:[match range]]);
}
Output:
2013-04-29 16:57:51.688 Had a
2013-04-29 16:57:51.689 #great
2013-04-29 16:57:51.690 time at the
2013-04-29 16:57:51.691 #party
2013-04-29 16:57:51.692 last night.
If you want to do it efficiently in a single pass on the string you can try something like (scratch code - test for bugs/boundary cases etc...):
int main (int argc, const char * argv[])
{
NSString *msg = #"Had a #great time at the #party last night.";
Boolean inTag = NO;
NSMutableArray *segments = [[NSMutableArray alloc] init];
NSUInteger idx = 0;
NSUInteger i=0;
for (; i < [msg length]; i++)
{
unichar ch = [msg characterAtIndex:i];
if (inTag && ch == ' ')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = NO;
}
if (ch == '#')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = YES;
}
}
if (i > idx)
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx - 1)]];
}
for(NSString *seg in segments)
{
NSLog(#"%#", seg);
}
}
This outputs:
2013-04-29 08:34:34.984 Craplet[95591:707] Had a
2013-04-29 08:34:34.986 Craplet[95591:707] #great
2013-04-29 08:34:34.986 Craplet[95591:707] time at the
2013-04-29 08:34:34.987 Craplet[95591:707] #party
2013-04-29 08:34:34.987 Craplet[95591:707] last night
Try this:
for (int i=0;i<[YourArray count];i++) {
NSString * mystr=[YourArray objectAtIndex:i];
NSString *temp=[mystr substringToIndex:1];
if (![temp isEqualToString:#"#"]) {
//add your string in new array and use this arry.....
}
}
try this code
for (int i=0;i<[YourArray count];i++) {
NSString * str=[YourArray objectAtIndex:i];
NSString *myString=[str substringToIndex:1];
NSString *stringfinal = [myString
stringByReplacingOccurrencesOfString:#"#" withString:#""];
}
Try using regular expressions. With this code you'll be able to extract the hashtags:
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((?:#){1}[\\w\\d]{1,140})" options:0 error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for ( NSTextCheckingResult* match in matches )
{
NSString * hashtag = [string substringWithRange:[match range]];
NSLog(#"match: %#", hashtag);
}
With this, you'll be able to build up the array result you're looking for.
Try
NSString *string = #"Had a #great time at the #party last night.";
NSArray *components = [string componentsSeparatedByString:#" "];
NSMutableArray *formattedArray = [NSMutableArray array];
NSMutableString *mutableString = [NSMutableString string];
for (NSString *string in components)
{
if (![string hasPrefix:#"#"]){
if (!mutableString){
mutableString = [NSMutableString string];
}
[mutableString appendFormat:#" %#",string];
}else{
if (mutableString) {
[formattedArray addObject:mutableString];
mutableString = nil;
}
[formattedArray addObject:string];
}
}
if (mutableString) {
[formattedArray addObject:mutableString];
}
NSLog(#"%#",formattedArray);
EDIT :
(
" Had a",
"#great",
" time at the",
"#party",
" last night."
)
One-pass solution with NSScanner
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject:s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
}
result:
(
"Had a ",
"#great",
"time at the ",
"#party",
"last night."
)
if you want to preserve the leading whitespace, alter it slightly to
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
BOOL firstSegment = YES;
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject: (!firstSegment) ? [#" " stringByAppendingString:s] : s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
firstSegment = NO;
}
result:
(
"Had a ",
"#great",
" time at the ",
"#party",
" last night."
)

Reverse strings in array objectivec [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse NSString text
i am new on objectovec. i have a array having strings. how to reverse each string?
which method of NSArray and NSstring will help me out?
i want reversed string in the array.
thanks
Create a method that will return a reversed string.
-(NSString *)reverseString:(NSString *)string{
NSString *reverseString=[NSString new];
for (NSInteger i=string.length-1; i>-1; i--) {
reverseString=[reverseString stringByAppendingFormat:#"%c",[string characterAtIndex:i]];
}
return reverseString;
}
In your any of the method :
NSMutableArray *names=[NSMutableArray arrayWithObjects:#"anoop",#"johnson",#"wasim",nil];
for (NSInteger i=0; i<names.count; i++) {
names[i]=[self reverseString:names[i]];
}
NSLog(#"%#",names);
Hope this help
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
AnOther way for revers string NSStringEnumerationOptions
- (NSString *)reverseString:(NSString *)string {
NSMutableString *reversedString = [[NSMutableString alloc] init];
NSRange fullRange = [string rangeOfString:string];
NSStringEnumerationOptions enumerationOptions = (NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences);
[string enumerateSubstringsInRange:fullRange options:enumerationOptions usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}
Use
unichar c[yourstring.Length];
NSRange raneg={0,yourstring.Length};
[yourstring getCharacters:c range:raneg];
//c will be an array of your string do what ever you wish
Use this one to reverse your string and then store back to your array at same index.
-(NSString*)reverseString:(NSString*)string {
NSMutableString *reversedString;
int length = [string length];
reversedString = [NSMutableString stringWithCapacity:length];
while (length--) {
[reversedString appendFormat:#"%c", [string characterAtIndex:length]];
}
return reversedString;
}
But if you have mutable string then you can create a category
#interface NSMutableString (Reverse)
- (void)reverseString;
#end
#implementation NSMutableString (Reverse)
- (void)reverseString {
for (int i = 0; i < self.length/2; i++) {
int l = self.length - 1 - i;
NSRange iRange = NSMakeRange(i, 1);
NSRange lRange = NSMakeRange(l, 1);
NSString *iStr = [self substringWithRange:iRange];
NSString *lStr = [self substringWithRange:lRange];
[self replaceCharactersInRange:iRange withString:lStr];
[self replaceCharactersInRange:lRange withString:iStr];
}
}
#end
And then you can use this category method like this
NSArray *arr = [NSArray arrayWithObjects:[#"hello" mutableCopy], [#"Do it now" mutableCopy], [#"Test string, 123 123" mutableCopy], nil];
NSLog(#"%#",arr);
[arr makeObjectsPerformSelector:#selector(reverseString)];
NSLog(#"%#",arr);

How to random sort a NSString

NSMutableString *str =#"abcdefg123";
I want random the every character to a new String like this #"f1ad2g3be2".
NSMutableString *str1 = [[NSMutableString alloc]initWithString:str];
NSMutableString *str2 = [[NSMutableString alloc] init];
while ([str1 length] > 0) {
int i = arc4random() % [str1 length];
NSRange range = NSMakeRange(i,1);
NSString *sub = [str1 substringWithRange:range];
[str2 appendString:sub];
[str1 replaceOccurrencesOfString:sub withString:#"" options:nil range:range];
}
[str1 release];
str2 is what u want
Quite simple. First you must break up the characters into an array to work with. Then you swap the letters X many times, I choose to do this so every character will be swapped
NSString *str =#"abcdefg123";
int length = str.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [str characterAtIndex:i]];
[letters addObject:letter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
NSString *results = [letters componentsJoinedByString:#""];
NSLog(#"The string before : %#", str);
NSLog(#"This is the string now : %#", results);

how to capture the required values from a URL

I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
http://gmail.com?access_token=ab8w4azq2xv3dr4ab37vvzmh&token_type=bearer&expires_in=3600
How can I capture the value of the access_token which in this example is ab8w4azq2xv3dr4ab37vvzmh?
This code should do it:
- (NSString *)extractToken:(NSURL *)URL
{
NSString *urlString = [URL absoluteString];
NSRange start = [urlString rangeOfString:#"access_token="];
if (start.location != NSNotFound)
{
NSString *token = [urlString substringFromIndex:start.location+start.length];
NSRange end = [token rangeOfString:#"&"];
if (end.location != NSNotFound)
{
//trim off other parameters
token = [token substringToIndex:end.location];
}
return token;
}
//not found
return nil;
}
Alternatively, here is a more general solution that will extract all the query parameters into a dictionary:
- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:#"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:#"="];
NSString *key = [[parts objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([parts count] > 1)
{
id value = [[parts objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[result setObject:value forKey:key];
}
}
return result;
}
Good Category for NSDictionary:
#import "NSDictionary+URL.h"
#implementation NSDictionary (URL)
+ (NSDictionary *)dictionaryWithUrlString:(NSString *)urlString{
NSRange urlRange = [urlString rangeOfString:#"?"];
if(urlRange.length>0){
urlString = [urlString substringFromIndex:urlRange.length+urlRange.location];
}
NSArray *pairsArray = [urlString componentsSeparatedByString:#"&"];
NSMutableDictionary *parametersDictionary = [[NSMutableDictionary alloc] initWithCapacity:[pairsArray count]];
for(NSString *pairString in pairsArray){
NSArray *valuesArray = [pairString componentsSeparatedByString:#"="];
if([valuesArray count]==2){
[parametersDictionary setValue:[valuesArray objectAtIndex:1] forKey:[valuesArray objectAtIndex:0]];
}
}
return [parametersDictionary autorelease];
}
#end
NSMutableDictionary *querycomponent = [[NSMutableDictionary alloc] init];
if (![query isEqualToString:#""]){
NSArray *queryArray = [query componentsSeparatedByString:#"&"];
for (NSString *subquery in queryArray){
NSArray *subqueryArray = [subquery componentsSeparatedByString:#"="];
NSString *key = [subqueryArray objectAtIndex:0];
NSString *val = [subqueryArray objectAtIndex:1];
[querycomponent setObject:val forKey:key];
}
NSLog(#"querycomponent %#",querycomponent);
}