Change the position of character in string - iphone

I have a two string like "SANFRANSICO" and "CHICAGO"
Now i want to make it like the string is in reverse but in a single string like "OOCGIASCNIAHRCFNAS"
I have done code but it gives me wrong result
check out my code
- (NSString *)changeString1:(NSString *)string string2:(NSString *)string2{
int first = [string length];
int second = [string2 length];
int total = first+second;
NSMutableString *str = [[NSMutableString alloc] init];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for (int i=0; i<total+1; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j+1]];
NSLog(#"222 %d %#",j+1, ichar );
[str appendString:ichar];
check = YES;
}
}
else {
int j = i/2;
if(check == YES){
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
NSLog(#"1111 %d %#",j, ichar );
[str appendString:ichar];
}
}
}
return str;
}

I found the answer very soon after post this question sorry for posting this question
check out my answer
- (NSString *)changeString1:(NSString *)string string2:(NSMutableString *)string2{
int first = [string length];
int second = [string2 length];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for(int i =second; i<first; i ++){
[string2 appendString:#" "];
}
int total = first*2;
NSMutableString *str = [[NSMutableString alloc] init];
for (int i=0; i<total; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
else {
int j = i/2;
if(j < first){
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
}
NSLog(#"str %#", str);
return str;
}

Related

Memory issues when using ABRecordCopyCompositeName

I have the following piece of code in displaying the mapview.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MKCoordinateRegion region = mapView.region;
MKCoordinateSpan span;
span.latitudeDelta=100;
span.longitudeDelta=100;
NSString *compositeName =(NSString*)ABRecordCopyCompositeName(person);
if([compositeName length] < 1){
firstName = #"No Name";
lastName = #"";
}
else if([firstName length] < 1 && [lastName length] < 1){
firstName = compositeName;
lastName = #"";
}
else if([firstName length] < 1)
{
firstName = lastName;
lastName = #"";
}
addAnnotation = [[[MyAnnotation alloc] initWithCoordinate:mapCenter title:firstName SubTitle:lastName ]autorelease];
[mapView addAnnotation:addAnnotation];
region.span=span;
region.center=mapCenter;
[pool release];
When analysing the project to check for memory leaks, I get the warning, "Potential leak of an object stored into compositeName". Should I release compositeName of type string.
Here object allocated and stored into 'compositeName' has a retain count of +1. I think you just need to release compositeName in this case.
This is Answer similar to my answer
please try below code for get all the information of people from phonebook
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
}
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}

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

nsstring replace string in range

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

How to convert HEX to NSString in Objective-C?

I have a NSString with hex string like "68656C6C6F" which means "hello".
Now I want to convert the hex string into another NSString object which shows "hello". How to do that ?
I am sure there are far better, cleverer ways to do this, but this solution does actually work.
NSString * str = #"68656C6C6F";
NSMutableString * newString = [[[NSMutableString alloc] init] autorelease];
int i = 0;
while (i < [str length])
{
NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
int value = 0;
sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
[newString appendFormat:#"%c", (char)value];
i+=2;
}
This should do it:
- (NSString *)stringFromHexString:(NSString *)hexString {
// The hex codes should all be two characters.
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:#"%c", decimalValue];
}
return string;
}
+(NSString*)intToHexString:(NSInteger)value
{
return [[NSString alloc] initWithFormat:#"%lX", value];
}
extension String {
func hexToString()-> String {
var newString = ""
var i = 0
while i < self.count {
let hexChar = (self as NSString).substring(with: NSRange(location: i, length: 2))
if let byte = Int8(hexChar, radix: 16) {
if (byte != 0) {
newString += String(format: "%c", byte)
}
}
i += 2
}
return newString
}
}
I think the people advising initWithFormat is the best answer as it's objective-C rather than a mix of ObjC, C.. (although the sample code is a bit terse).. I did the following
unsigned int resInit = 0x1013;
if (0 != resInit)
{
NSString *s = [[NSString alloc] initWithFormat:#"Error code 0x%lX", resInit];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Initialised failed"
message:s
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[s release];
}

Subtracting 2 strings

I have a string say for example #"012" and I have another string #"02". How can I extract the difference of the 2 strings in iPhone Objective-C. I just need to remove the existence of the characters in the 2nd string from the first string.The answer would be "1".
Even shorter:
NSString* s1 = #"012";
NSString* s2 = #"02";
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:s2];
NSString * final = [[s1 componentsSeparatedByCharactersInSet:set] componentsJoinedByString:#""];
NSLog(#"Final: %#", final);
This preserves the order of the characters in the original string.
You could do something like this;
NSString *s1 = #"012";
NSString *s2 = #"02";
NSCharacterSet *charactersToRemove;
charactersToRemove = [NSCharacterSet characterSetWithCharactersInString:s2];
NSMutableString *result = [NSMutableString stringWithCapacity:[s1 length]];
for (NSUInteger i = 0; i < [s1 length]; i++) {
unichar c = [s1 characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[result appendFormat:#"%C", c];
}
}
// if memory is an issue:
result = [[result copy] autorelease];
Disclaimer: I typed this into the browser, and haven't tested any of this.
You're trying to do a set operation, so use sets.
{
NSString* s1 = #"012";
NSString* s2 = #"02";
NSMutableSet* set1 = [NSMutableSet set];
NSMutableSet* set2 = [NSMutableSet set];
for(NSUInteger i = 0; i < [s1 length]; ++i)
{
[set1 addObject:[s1 substringWithRange:NSMakeRange(i, 1)]];
}
for(NSUInteger i = 0; i < [s2 length]; ++i)
{
[set2 addObject:[s2 substringWithRange:NSMakeRange(i, 1)]];
}
[set1 minusSet:set2];
NSLog(#"set1: %#", set1);
// To get a single NSString back from the set:
NSMutableString* result = [NSMutableString string];
for(NSString* piece in set1)
{
[result appendString:piece];
}
NSLog(#"result: %#", result);
}
I simply used "componentsSeparatedByString"
NSString *s1 = #"abc";
NSString *s2 = #"abcdef";
//s2 - s1
NSString * final = [[s2 componentsSeparatedByString:s1] componentsJoinedByString:#""];