I have three type of string and i want to format that string to get street number, street name, city name.
The first type is : 34 Ellis Street, San Francisco
Here i want to make it like
street number : 34
street name : Ellis Street
city name : San Francisco
The second type is : 4FL, 800 Market Street, San Francisco
Here i want to delete 4FL,
And i want to make it like
street number : 800
street name : Market Street
city name : San Francisco
The third type is : Ellis & Market, San Francisco
Here i want to make it like
street number :
street name : Ellis & Market
city name : San Francisco
How can i do this or any link that show string formatting like this than please suggest.And yes the string i write here is just a format of string i get,string will be changed every time.
The address string is passed to this method and then it is converted into an array having 3 string objects containing streetNumber, streetName and cityName. Then the array is returned to the caller.
-(NSArray *)brakeAddress:(NSString *)address{
NSMutableArray *arr=[NSMutableArray arrayWithArray:[address componentsSeparatedByString:#","]];
if (arr.count>2) {
[arr removeObjectAtIndex:0];
}
NSInteger streetNameInd=[arr count]-2, cityNameInd=[arr count]-1;
NSMutableArray *streetNameArray=[NSMutableArray arrayWithObjects:arr[0], nil];
if ([arr[streetNameInd] intValue]) {
streetNameArray=[NSMutableArray arrayWithArray:([arr[streetNameInd] componentsSeparatedByString:#" "])];
[streetNameArray removeObjectAtIndex:0];
if ([streetNameArray[0] intValue] ==[arr[streetNameInd] intValue]) {
[streetNameArray removeObjectAtIndex:0];
}
}
NSString *streetName=[streetNameArray componentsJoinedByString:#" "];
NSString *streetNumber=#"";
if ([arr[streetNameInd] intValue]!=0) {
streetNumber=[NSString stringWithFormat:#"%d", [arr[streetNameInd] intValue]];
}
NSString *city=arr[cityNameInd];
// NSLog(#"\nstreet number :%#\nstreet name :%#\ncity name :%#",streetNumber, streetName,city);
NSArray *addressParts=[NSArray arrayWithObjects:streetNumber, streetName, city, nil];
return addressParts;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
NSString *str1=#"34 Ellis Street, San Francisco";
NSString *str2=#"4FL, 800 Market Street, San Francisco";
NSString *str3=#"Ellis & Market, San Francisco";
NSArray *firstAddress=[self brakeAddress:str1];
NSArray *secondAddress=[self brakeAddress:str2];
NSArray *thirdAddress=[self brakeAddress:str3];
NSLog(#"\n1st : street number :%#\nstreet name :%#\ncity name :%#",firstAddress[0],firstAddress[1],firstAddress[2]);
NSLog(#"\n2nd : street number :%#\nstreet name :%#\ncity name :%#",secondAddress[0],secondAddress[1],secondAddress[2]);
NSLog(#"\n3rd : street number :%#\nstreet name :%#\ncity name :%#",thirdAddress[0],thirdAddress[1],thirdAddress[2]);
}
1) Separate with:
NSArray *arrayOfComponents = [yourString componentsSeparatedByString:#","];
2) The last component will always be your city name
3) Then check the (Last - 1) component with
NSArray *array = [yourString componentsSeparatedByString:#" "];
2) Take the FIRST element of the array and use this
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
// newString consists only of the digits 0 through 9
}
3) If it has only digits then, the FIRST element is your street number, and just make a new string by appending the remaining elements to get the street name. Else the past (last -1) from the previous array is the street name.
This is the basic idea, the logic can obviously be improved.
Edit: since you mentioned that this string is provided by google api it means you are probably getting a JSON response. You should use the complete JSON response to get your textfields filled. There is a JSON to NSDictionary Class you can use:see here
May be first you can implement code to break the address string into different variables such as _streetNum,_streetName,_cityName then you can use following code line for formatting the string
NSString* formattedString = [[NSString alloc] initWithFormat:#"street number : %#\nstreet name :%#\ncity name :%#",_streetNum,_streetName,_cityName];
Try this:
NSArray *array = [yourString componentsSeparatedByString:#" "];
It will give you an array wsth all strings separated by " ";
Try in the following way and parse the response whatever you need related to that address
http://maps.googleapis.com/maps/api/geocode/json?address=34%20Ellis%20Street,%20San%20Francisco,+CA&sensor=true
HOpe it may help you.
You need to use Regular Expressions. Have a look at this: Regular Expressions
Here is a piece of code that might help you.
NSString *addressString;
NSArray *tempArray = [addressString componentsSeparatedByString:#", "];
if([tempArray count]==3){
city = [tempArray objectAtIndex:2];
NSString *tempString = [tempArray objectAtIndex:1];
NSArray *temp1Array = [tempString componentsSeparatedByString:#" "];
if ([temp1Array count]>1) {
st_num = [tempArray objectAtIndex:0];
st_name = [tempString stringByReplacingOccurrencesOfString:
[NSString stringWithFormat:#"%# ",st_num] withString:#""];
}
}
You can extend its logic for your requirement.
Related
NSString * str=[zoneDict objectForKey:#"name"];
NSLog(#"==========string zone::==========%#",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
How can I get the 3:00 value from the above string?
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSRange endRange = [str rangeOfString:#")"];
NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
NSRange separatorRange = [timeString rangeOfString:#":"];
NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
NSLog(#"Hour:%d",hourInt);
Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict? For example you could store NSTimeZone instances instead.
If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.
If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.
I like to use -[NSString componentsSeparatedByString]:
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:#")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:#"-"].location == NSNotFound) {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"+"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
else {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"-"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
Output:
Your String - 3:00
Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.
All,
I have a dictionary with two keys and values. I need to extract bits and pieces from them and place them into seperate strings.
{
IP = "192.168.17.1";
desc = "VUWI-VUWI-ABC_Dry_Cleaning-R12-01";
}
That is what the dictionary looks like when I call description.
I want the new output to be like this:
NSString *IP = #"192.168.17.1";
NSString *desc = #"ABC Dry Cleaning"; //note: I need to get rid of the underscores
NSString *type = #"R";
NSString *num = #"12";
NSString *ident = #"01";
How would I achieve this?
I've read through the Apple developer docs on NSRegularExpression but I find it hard to understand. I'm sure once I get some help once here I can figure it out in the future, I just need to get started.
Thanks in advance.
Okay, so first, you have to get the object associated with each key:
NSString *ip = [dic objectForKey:#"IP"]; //Btw, you shouldn't start a variable's name with a capital letter.
NSString *tempDesc = [dic objectForKey:#"desc"];
Then, what I would do is split the string in tempDesc, based on the character -.
NSArray *tmpArray = [tempDesc componentsSeparatedByString:#"-"];
Then you just have to get the strings or substrings you're interested in, and reformat them as needed:
NSString *desc = [[tmpArray objectAtIndex:2] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *type = [[tmpArray objectAtIndex:3] substringToIndex:1];
NSString *num = [[tmpArray objectAtIndex:3] substringFromIndex:1];
NSString *ident = [tmpArray objectAtIndex:4];
As you can see, this works perfectly without using NSRegularExpression.
I want to extract the phone number from a NSString.
For ex: In the string Call John # 994-456-9966, i want to extract 994-456-9966.
I have tried code like,
NSString *nameRegex =#"(\(\d{3}\)\s?)?\d{3}[-\s\.]\d{4}";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:#"ANY keywords.name CONTAINS[c] %#",nameRegex];
validationResult=[nameTest evaluateWithObject:phoneNo];
but i couldnt get exact result. Can anyone help me? Thanks in advance.
This is what you are looking for, I think:
NSString *myString = #"John # 123-456-7890";
NSString *myRegex = #"\\d{3}-\\d{3}-\\d{4}";
NSRange range = [myString rangeOfString:myRegex options:NSRegularExpressionSearch];
NSString *phoneNumber = nil;
if (range.location != NSNotFound) {
phoneNumber = [myString substringWithRange:range];
NSLog(#"%#", phoneNumber);
} else {
NSLog(#"No phone number found");
}
You can rely on the default Regular Expression search mechanism built into Cocoa. This way you will be able to extract the range corresponding to the phone number, if present.
Remember do alway double-escape backslashes when creating regular expressions.
Adapt your regex accordingly to the part of the phone number you'd like to extract.
Edit
Cocoa provides really simple tools for handling regular expressions. For more complex needs, you should look at the powerful RegexKitLite extension for Cocoa projects.
You can check the official NSDataDetector in iOS 4.0
phoneLinkDetector = [[NSDataDetector alloc] initWithTypes:
(NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber) error:nil];
NSUInteger numberOfPhoneLink = [[self phoneLinkDetector] numberOfMatchesInString:tweet
options:0 range:NSMakeRange(0, tweet.length)];
NSString * number = #"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:#"[^0-9]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];
Result: 555555555
if u need just the number u can filter out the special characters and use nsscanner
NSString *numberString = #"Call John # 994-456-9966";
NSString *filteredString=[numberString stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSScanner *aScanner = [NSScanner scannerWithString:filteredString];
[aScanner scanInteger:anInteger];
Assume that you are having "#" symbol in all phone numbers.
NSString *list = #"Call John # 994-456-9966";
NSArray *listItems = [list componentsSeparatedByString:#"#"]
or
You can use the NSScanner to extract the phone number.
EDIT:After seeing the comments.
Assume that you are having only 12 characters in your mobile numbers.
length=get the total length of the string.
index=length-12;
NSString *str=[myString substringFromIndex:index];
i have the text in a string as shown below
011597464952,01521545545,454545474,454545444|Hello this is were the message is.
Basically i would like each of the numbers in different strings to the message eg
NSString *Number1 = 011597464952
NSString *Number2 = 01521545545
etc
etc
NSString *Message = Hello this is were the message is.
i would like to have that split out from one string that contains it all
I would use -[NSString componentsSeparatedByString]:
NSString *str = #"011597464952,01521545545,454545474,454545444|Hello this is were the message is.";
NSArray *firstSplit = [str componentsSeparatedByString:#"|"];
NSAssert(firstSplit.count == 2, #"Oops! Parsed string had more than one |, no message or no numbers.");
NSString *msg = [firstSplit lastObject];
NSArray *numbers = [[firstSplit objectAtIndex:0] componentsSepratedByString:#","];
// print out the numbers (as strings)
for(NSString *currentNumberString in numbers) {
NSLog(#"Number: %#", currentNumberString);
}
Look at NSString componentsSeparatedByString or one of the similar APIs.
If this is a known fixed set of results, you can then take the resulting array and use it something like:
NSString *number1 = [array objectAtIndex:0];
NSString *number2 = [array objectAtIndex:1];
...
If it is variable, look at the NSArray APIs and the objectEnumerator option.
NSMutableArray *strings = [[#"011597464952,01521545545,454545474,454545444|Hello this is were the message is." componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#",|"]] mutableCopy];
NString *message = [[strings lastObject] copy];
[strings removeLastObject];
// strings now contains just the number strings
// do what you need to do strings and message
....
[strings release];
[message release];
does objective-c have strtok()?
The strtok function splits a string into substrings based on a set of delimiters.
Each subsequent call gives the next substring.
substr = strtok(original, ",|");
while (substr!=NULL)
{
output[i++]=substr;
substr=strtok(NULL, ",|")
}
Here's a handy function I use:
///Return an ARRAY containing the exploded chunk of strings
///#author: khayrattee
///#uri: http://7php.com
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}
The following code creates me an array of all my contacts in my address book by first name and last name. The problem is, I have one contact that keeps showing up with an empty first name and last name. I can't find that contact in my actual address book. Can anyone suggest how to debug this to figure out the source of the mystery ghost contact?
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *peopleArray = (NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *allNames = [NSMutableArray array];
for (id person in peopleArray) {
NSMutableString *firstName = [(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty) autorelease];
NSMutableString *lastName = [(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty) autorelease];
ABMutableMultiValueRef multiValueEmail = ABRecordCopyValue(person, kABPersonEmailProperty);
if (ABMultiValueGetCount(multiValueEmail) > 0) {
NSString *email = [(NSString *)ABMultiValueCopyValueAtIndex(multiValueEmail, 0) autorelease];
}
if (![firstName length]) {
firstName = #"";
}
if (![lastName length]) lastName = #"";
[allNames addObject:[NSString stringWithFormat:#"%# %#", firstName, lastName]];
}
The person type is of type NSCFType. I could easily do something like:
if (![lastName length] && ![firstName length]) continue;
.. and be done with the problem. I'm curious though what entry in my AddressBook is coming up as a ghost. I've tried introspecting the object with gdb, but can't get anything valuable out of it.
I'd like to see all properties for person, but derefing the object to (ABPerson*) doesn't appear to do it.
I've also tried using CFShow(person) that reveals it to be type CPRecord. Can't find further documentation on that, however.
Is there something in gdb I can do to further inspect this particular person object to see where the source of it is coming from?
The entry is probably flagged as an organization record, rather than a person record. In this case you'll have to pull out the organization name rather than the first and last name.
Try looking at the properties for:
kABPersonOrganizationProperty, kABPersonKindProperty
IT is probably a contact that is only an organization
try looking at these properties
These constants implement the person type property (a property of
type kABIntegerPropertyType), which
indicates whether a person record
represents a human being or an
organization.
const ABPropertyID kABPersonKindProperty;
const CFNumberRef kABPersonKindPerson;
const CFNumberRef kABPersonKindOrganization;