iPhone:Convert NSString 123-123-1234 into (123) 123-1234 - iphone

I have string like 123-123-1234 so I want to convert string into this format
(123) 123-1234 so any idea to develop this functionality.
Thanks in advance.

I think something like this:
NSString *list = #"123-123-1234";
NSArray *listItems = [list componentsSeparatedByString:#"-"];
NSString *result = [NSString stringWithFormat:#"(%#) %#-%#", [listItem objectAtIndex:0], [listItem objectAtIndex:1], [listItem objectAtIndex:2]];

NSString * original = #"123-123-1234";
NSArray * components = [original componentsSeparatedByString:#"-"];
NSString * first = [NSString stringWithFormat:#"(%#)",[components objectAtIndex:0] ];
NSString * second = [NSString stringWithFormat:#"%#-%#",[components objectAtIndex:1],[components objectAtIndex:2]];
NSString * finalString = [NSString stringWithFormat:#"%#%#",first,second];
NSLog(#"Final Result = %#",finalString);

NSString *str = #"123-123-1234";
NSArray *arrForDate = [str componentsSeparatedByString: #"-"];
NSString *str1 = [NSString stringWithFormat:#"(%#) %#-%#",[arrForDate objectAtIndex:0],[arrForDate
objectAtIndex:1],[arrForDate objectAtIndex:2]];
NSLog(#"str1 %#",str1);

TESTED CODE: 100% WORKS
NSString *inputString=#"123-123-1234";
NSArray *TotalString=[inputString componentsSeparatedByString:#"-"];
NSString *outputString = [NSString stringWithFormat:#"(%#) %#-%#",[TotalString objectAtIndex:0],[TotalString objectAtIndex:1],[TotalString objectAtIndex:2]];
NSLog(#"outputString is : %# \n\n",outputString);
OUTPUT:
outputString is : (123) 123-1234
For Dynamic Sollution:
NOTE: if u have more dashes with ur string then it is really hard code everything with objectAtIndex with number 0,1,2,....
moreover it will crash if it has unexpected length
so here is the solution for this
NSString *inputString=#"123-123-1234";
NSArray *TotalString=[inputString componentsSeparatedByString:#"-"];
NSMutableString *outputString=[NSMutableString string];
for (NSMutableString *obj in TotalString) {
if ([TotalString objectAtIndex:0] == obj && [outputString length]<=0) {
outputString=[[outputString stringByAppendingFormat:#"(%#)",obj] mutableCopy];
}
else if ([TotalString objectAtIndex:1] == obj) {
outputString=[[outputString stringByAppendingFormat:#"%#%#",#" ",obj] mutableCopy];
}
else {
outputString=[[outputString stringByAppendingFormat:#"-%#",obj] mutableCopy];
}
}
OUTPUT:
outputString is : (123) 123-1234

NSString *list = #"123-123-1234";
NSArray *listItems = [list componentsSeparatedByString:#"-"];
NSString *result = [NSString stringWithFormat:#"(%#) %#-%#", [listItem objectAtIndex:0], [listItem objectAtIndex:1], [listItem objectAtIndex:2]];

Related

how to pass data from one entity to other entity class?

i am getting all chapters in my chapterDC class and also getting regions, i have a property of selectedRegion in my chapterDC class and want to pass my region data into regionDC through chapterDC,but my log message is always 0 and null, i don t know what mistake i am doing
-(NSMutableArray *)getAllChapters
{
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"%#get_all_chapters",kWSURL];
NSDictionary * returnDict = (NSDictionary *) [self callWebService:url];
if([[returnDict objectForKey:#"status"] isEqualToString:#"success"])
{
NSDictionary * responseDict = (NSDictionary *) [returnDict objectForKey:#"response"];
NSArray *resultArray = [responseDict objectForKey:#"result"];
for(NSDictionary *chapterDict in resultArray)
{
ChapterDC * chapter = [[ChapterDC alloc] init];
chapter.ChapterDC_ChapterID=[[chapterDict objectForKey:#"ChapterID"]intValue];
chapter.ChapterDC_ChapterName = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"ChapterName"]];
chapter.selectedRegion.RegionDC_RegionID=[ [chapterDict objectForKey:#"RegionID"]intValue];
NSLog(#"%d",chapter.selectedRegion.RegionDC_RegionID);
chapter.ChapterDC_AddressLine1 = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"AddressLine1"]];
chapter.ChapterDC_AddressLine2 = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"AddressLine2"]];
chapter.ChapterDC_AddressLine3 = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"AddressLine3"]];
chapter.ChapterDC_Email = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"Email"]];
chapter.ChapterDC_URL = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"URL"]];
chapter.ChapterDC_FacebookURL =[ NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"FacebookURL"]];
chapter.ChapterDC_LinkedInURL = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"LinkedInURL"]];
chapter.ChapterDC_PhoneNumber =[ NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"PhoneNumber"]];
chapter.ChapterDC_Postcode = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"Postcode"]];
chapter.ChapterDC_TwitterURL = [NSString stringWithFormat:#"%#", [chapterDict objectForKey:#"TwitterURL"]];
NSDictionary * regionDict = (NSDictionary *) [returnDict objectForKey:#"region"];
{
chapter.selectedRegion = [[RegionDC alloc] init];
chapter.selectedRegion.RegionDC_RegionID = [[regionDict objectForKey:#"RegionID"]intValue];
NSLog(#"%d",chapter.selectedRegion.RegionDC_RegionID);
chapter.selectedRegion.RegionDC_RegionName = [NSString stringWithFormat:#"%#", [regionDict objectForKey:#"RegionName"]];
NSLog(#"%#",chapter.selectedRegion.RegionDC_RegionName);
chapter.selectedRegion.RegionDC_ContactName = [NSString stringWithFormat:#"%#", [regionDict objectForKey:#"ContactName"]];
chapter.selectedRegion.RegionDC_Mobile = [NSString stringWithFormat:#"%#", [regionDict objectForKey:#"Mobile"]];
chapter.selectedRegion.RegionDC_Landline = [NSString stringWithFormat:#"%#", [regionDict objectForKey:#"Landline"]];
chapter.selectedRegion.RegionDC_TrainingURL = [NSString stringWithFormat:#"%#", [regionDict objectForKey:#"TrainingURL"]];
}
[returnArray addObject:chapter];
}
}
return returnArray;
}
Replace NSDictionary * regionDict = (NSDictionary *) [returnDict objectForKey:#"region"];
with
NSDictionary * regionDict = (NSDictionary *) [chapterDict objectForKey:#"region"];

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

remove last digits from float value,iPhone

I have a float value say 28.980000.
I want something like that 28.98, only 2 values after decimal.
How can i do this ?
Regards
One of the easiest solutions would be to use stringWithFormat: of NSString:
NSString* result = [NSString stringWithFormat: #"%5.2f", floatVal];
Try this..
-(NSString*)floatToString:(float)val
{
NSString *result;
NSArray *numbers = [[NSArray alloc]initWithObjects:[NSString stringWithFormat:#"%f",val], nil];
NSLog(#"%#",numbers);
NSArray * floatingPoint = [[numbers objectAtIndex:0] componentsSeparatedByString:#"."];
NSString * lastObject = [[floatingPoint lastObject] stringByReplacingOccurrencesOfString:#"0" withString:#""];
if ([lastObject length] < 2) {
result = [NSString stringWithFormat:#"$ %.2f",[[numbers objectAtIndex:0] floatValue]];
} else {
result = [NSString stringWithFormat:#"$ %g",[[numbers objectAtIndex:0] floatValue]];
}
return result;
}

How to convert string to array in objective C?

How to convert string to array in objective C. i.e,I have a string,
NSString *str = #"Hi,How r u";
This should be converted into an array *NSMutableArray arr , where in
arr[0] = "Hi"
arr[1] = ","
arr[2] = "How"
arr[3] = "r"
arr[4] = "u"
Can anybody help with the idea to crack this thing.
NSString *str=#"Hi,How r u";
NSArray *arr = [str componentsSeparatedByString:#","];
NSString *strSecond = [arr objectAtIndex:1];
NSMutableArray *arrSecond = [strSecond componentsSeparatedByString:#" "];
NSString *strHow = [arr objectAtIndex:0];
NSString *strAre = [arr objectAtIndex:1];
NSString *strYou = [arr objectAtIndex:2];
[arr removeObjectAtIndex:1];
[arr addObject:#","];
[arr addObject:strHow];
[arr addObject:strAre];
[arr addObject:strYou];
arr is the desired array.
I guess this link will help you.
NSString *str = #"Hi,How r u";
NSArray *listItems = [str componentsSeparatedByString:#","];
You have to do,
NSString *str = #"Hi,How r u";
NSArray *arr = [str componentsSeparatedByString:#" "];
And, in order for this to work as you expect, there should be a white-space between "Hi," and "How". Your string should look like #"Hi, How r u".
try this
NSString *str2=#"Hi,How r u";
NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]]];
NSLog(#"%#",arary);
if you want , as a object
NSString *str2=#"Hi,How r u";
str2 = [str2 stringByReplacingOccurrencesOfString:#"," withString:#" , "];
NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByString:#" "]];
NSLog(#"%#",arary);
You can use the NSString method componentsSeparatedByString. Take a look at the reference here.

how can I convert string to an array with separator?

I have a string in the following format
myString = "cat+dog+cow"
I need to store each string separated by + in to a array.
Eg:
myArray[0] = cat
myArray[1] = dog
myArray[2] = cow
Can anyone tell me the proper way to do this?
componentsSeparatedByString: splits the string and return the result in an array.
NSArray *myArray = [myString componentsSeparatedByString:#"+"];
[myArray objectAtIndex:0];//cat
[myArray objectAtIndex:1];//dog
[myArray objectAtIndex:2];//cow
Try this..
NSArray *arr = [myString componentsSeparatedByString:#"-"];
[arr objectAtIndex:0];//Hai
[arr objectAtIndex:1];//Welcome
It is vert simple..
NSString * test = #"Hello-hi-splitting-for-test";
NSArray * stringArray = [test componentsSeparatedByString:#"-"];
// Now stringArray will contain all splitted strings.. :)
Hope this helps...
I you don't want use array then iterate through each character...
NSMutableString * splittedString = nil;
for(int i=0;i<test.length;i++){
unichar character = [test characterAtIndex:0];
if (character=='-') {
if (splittedString!=nil) {
NSLog(#"String component %#",splittedString);
[splittedString release];
splittedString = nil;
}
} else {
if (splittedString==nil) {
splittedString = [[NSMutableString alloc] init];
}
[splittedString appendFormat:#"%C",character];
}
}
if (splittedString!=nil) {
NSLog(#"String last component %#",splittedString);
[splittedString release];
splittedString = nil;
}
Thats all...
NSArray *myWords = [myString componentsSeparatedByString:#"+"];
You can find this one very simple
NSString *str = #"cat+dog+cow";
NSArray *arr = [str componentsSeparatedByString:#"+"];
NSLog(#"Array items %#",arr);
OUTPUT:
Array items
(
Cat,
dog,
Cow
)
Use the componentsSeparatedByString: method of NSString.
NSString string = #"hai-welcome";
NSArray myArray = [string componentsSeparatedByString:#"-"];
NSString* haiString = [myArray objectAtIndex:0];
NSString* welcomeString = [myArray objectAtIndex:1];
NSArray *strArray = [myString componentsSeparatedByString:#"-"];
firstString = [strArray objectAtIndex:0];//Hai
secondString = [strArray objectAtIndex:1];//Welcome
This will be the solution if you are dealing with a string:
NSString *mySstring = #"hai-welcome";
NSMutableArray *anArray=[[NSMutableArray alloc] initWithArray:[componentsSeparatedByString: #"-"]];
And each word will be stored in respective position from 0-n.
Try This. :)
If you are averse to using arrays, you can consider this –
NSString *accessMode, *message;
NSScanner *scanner = [NSScanner scannerWithString:#"hai-welcome"];
NSCharacterSet *hyphenSet = [NSCharacterSet characterSetWithCharactersInString:#"-"];
[scanner scanUpToCharactersFromSet:hyphenSet intoString:&accessMode];
[scanner scanCharactersFromSet:hyphenSet intoString:nil];
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:#""] intoString:&message];
NSArray *lines = [string componentsSeparatedByString:#"-"];
The first value will be stored in 0th index of lines and second value will be stored in 1th index of lines..
Why not array?
Simple code :
NSString *myString = [[NSString alloc] initWithString:#"cat+dog+cow"];
NSArray *resultArray = [tempString componentsSeparatedByString:#"+"];
NSLog(#"1. %# 2. %# 3. %#",[resultArray objectAtIndex:0],[resultArray objectAtIndex:1],[resultArray objectAtIndex:2]);
Try This:
NSString *str = #"cat+dog+cow" ;
NSArray *array = [str componentsSeparatedByString:#"+"];
NSLog(#"%#",array) ;