String Operation - iphone

If there is an NSString like "com.mycompany.purchase1" How to get only purchase1.
NSString *mainString = #"com.mycompany.purchase1";
-(NSString*)getLastComponent : (NSString*) mainString
{
NSString *string;
//Implementation
return string;//It should return only "purchase1"
}
I tried using lastPathComponent,pathExtension and also i can't use substringToIndex since the string may be of varying length.

Don't want donkim's answer as he is correct. Just showing the implementation I would use
-(NSString*)lastComponentOfString:(NSString*)string separatedByString:(NSString*)separator
{
return [[string componentsSeparatedByString:separator] lastObject];
}
Use
NSString *string = #"com.mycompany.purchase1";
[... lastComponentOfString:string separatedByString:#"."];

You could use the - (NSArray *)componentsSeparatedByString:(NSString *)separator method in NSString. Check to see that NSArray has a count greater than 0 and the last component of it ([array objectAtIndex:[array count] - 1]) will be what you want.

-(NSString*)getLastComponent : (NSString*) mainString
{
NSString *string1;
NSArray *arr=[mainString componentsSeparatedByString:#"."];
string1=[arr objectAtIndex:([arr count]-1)];
return string;
}
use above code.

Related

Parsing XML from NSString to get values

This question is for manipulating NSString in xcode.
I have a XML text string that I get from the web that looks like this
<current temperature="73" day="Mon" humidity="59" windspeed="10"></current>
How can I get individual values from this string and put them in my NSString variables?
e.g.
NSString *tempStr = ??
NSString *dayStr = ??
NSString *windspeedStr = ??
First, download and include RaptureXML within your project as described on the RaptureXML project site.
For parsing the single given line, use the following snippet - your input is passed as inXmlString;
//transform string into an XML DOM
RXMLElement *rootNode = [RXMLElement elementFromXMLString:inXmlString
withEncoding:NSUTF8StringEncoding];
if (rootNode == nil || ![rootNode isValid])
{
//do something, we failed!
}
else
{
NSString *temperature = [rootNode attribute:#"temperature"];
NSString *day = [rootNode attribute:#"day"];
NSString *windspeed = [rootNode attribute:#"windspeed"];
}
The basic idea is to use the NSString method componentsSeparatedByString: to parse out the data you want. You'll probably need to do a bit more work to get it exactly right for your scenario.
NSArray* paArray1= [pstrXMLString componentsSeparatedByString:#" "];
temlStr= [[[paArray1 objectAtIndex:1] componentsSeparatedByString:#"="] objectAtIndex:1];
dayStr= [[[paArray1 objectAtIndex:2] componentsSeparatedByString:#"="] objectAtIndex:1];
windspeedStr= [[[paArray1 objectAtIndex:3] componentsSeparatedByString:#"="] objectAtIndex:1];

Convert String into special - splitting an NSString

I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?
the following gives you the desired result:
NSString *_inputString = #"\"mocktail, wine, beer\"";
NSLog(#"input string : %#", _inputString);
NSLog(#"output string : %#", [_inputString stringByReplacingOccurrencesOfString:#", " withString:#"\", \""]);
the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
You need to use:
NSArray * components = [myString componentsSeparatedByString: #", "];
NSString *string = #"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:#","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSString *trimmedString in array) {
NSString *newString = [NSMutableString stringWithFormat:#"'%#'", trimmedString];
[newArray addObject:newString];
}
//merge new strings
NSString *finalString = [NSString stringWithFormat:#"%#", [newArray objectAtIndex:0]];
for (NSInteger i = 1; i < [newArray count]; i++) {
finalString = [NSString stringWithFormat:#"%#, %#", finalString, [newArray objectAtIndex:i]];
}
Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

IOS : NSString retrieving a substring from a string

Hey I am looking for a way to extract a string from another string. It could be any length and be in any part of the string so the usual methods don't work.
For example
http://bla.com/bla?id=%1234%&something=%888%
What I want to extract is from id=% to the next %.
Any idea's?
Use the rangeOfString method:
NSRange range = [string rangeOfString:#"id=%"];
if (range.location != NSNotFound)
{
//range.location is start of substring
//range.length is length of substring
}
You can then chop up the string using the substringWithRange:, substringFromIndex: and substringToIndex: methods to get the bits you want. Here's a solution to your specific problem:
NSString *param = nil;
NSRange start = [string rangeOfString:#"id=%"];
if (start.location != NSNotFound)
{
param = [string substringFromIndex:start.location + start.length];
NSRange end = [param rangeOfString:#"%"];
if (end.location != NSNotFound)
{
param = [param substringToIndex:end.location];
}
}
//param now contains your value (or nil if not found)
Alternatively, here's a general solution for extracting query parameters from a URL, which may be more useful if you need to do this several times:
- (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:#"="];
if ([parts count] > 1)
{
NSString *key = [parts[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [parts[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
result[key] = value;
}
}
return result;
}
This doesn't strip the % characters from the values, but you can do that either with
NSString *value = [[value substringToIndex:[value length] - 1] substringFromIndex:1];
Or with something like
NSString *value = [value stringByReplacingOccurencesOfString:#"%" withString:#""];
UPDATE: As of iOS 8+ theres a built-in class called NSURLComponents that can automatically parse query parameters for you (NSURLComponents is available on iOS 7+, but the query parameter parsing feature isn't).
Try this
NSArray* foo = [#"10/04/2011" componentsSeparatedByString: #"/"];
NSString* day = [foo objectAtIndex: 0];

how to remove () charracter

when i convert my array by following method , it adds () charracter.
i want to remove the () how can i do it..
NSMutableArray *rowsToBeDeleted = [[NSMutableArray alloc] init];
NSString *postString =
[NSString stringWithFormat:#"%#",
rowsToBeDeleted];
int index = 0;
for (NSNumber *rowSelected in selectedArray)
{
if ([rowSelected boolValue])
{
profileName = [appDelegate.archivedItemsList objectAtIndex:index];
NSString *res = [NSString stringWithFormat:#"%d",profileName.userID];
[rowsToBeDeleted addObject:res];
}
index++;
}
UPDATE - 1
when i print my array it shows like this
(
70,
71,
72
)
Here's a brief example of deleting the given characters from a string.
NSString *someString = #"(whatever)";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#"()"];
NSMutableString *mutableCopy = [NSMutableString stringWithString:someString];
NSRange range;
for (range = [mutableCopy rangeOfCharacterFromSet:charSet];
range.location != NSNotFound;
[mutableCopy deleteCharactersInRange:range],
range = [mutableCopy rangeOfCharacterFromSet:charSet]);
All this does is get a mutable copy of the string, set up a character set with any and all characters to be stripped from the string, and find and remove each instance of those characters from the mutable copy. This might not be the cleanest way to do it (I don't know what the cleanest is) - obviously, you have the option of doing it Ziminji's way as well. Also, I abused a for loop for the hell of it. Anyway, that deletes some characters from a string and is pretty simple.
Try using NSArray’s componentsJoinedByString method to convert your array to a string:
[rowsToBeDeleted componentsJoinedByString:#", "];
The reason you are getting the parenthesis is because you are calling the toString method on the NSArray class. Therefore, it sounds like you just want to substring the resulting string. To do this, you can use a function like the following:
+ (NSString *) extractString: (NSString *)string prefix: (NSString *)prefix suffix: (NSString *)suffix {
int strLength = [string length];
int begIndex = [prefix length];
int endIndex = strLength - (begIndex + [suffix length]);
if (endIndex > 0) {
string = [string substringWithRange: NSMakeRange(begIndex, endIndex)];
}
return string;
}

method with 2 return values

I want to call a method which returns two values
basically lets say my method is like the below (want to return 2 values)
NSString* myfunc
{
NSString *myString = #"MYDATA";
NSString *myString2 = #"MYDATA2";
return myString;
return myString2;
}
So when i call it, i would use??
NSString* Value1 = [self myfunc:mystring];
NSString* Value2 = [self myfunc:mystring2];
I guess im doing something wrong with it, can anyone help me out?
Thanks
You can only return 1 value. That value can be a struct or an object or a simple type. If you return a struct or object it can contain multiple values.
The other way to return multiple values is with out parameters. Pass by reference or pointer in C.
Here is a code snippet showing how you could return a struct containing two NSStrings:
typedef struct {
NSString* str1;
NSString* str2;
} TwoStrings;
TwoStrings myfunc(void) {
TwoStrings result;
result.str1 = #"data";
result.str2 = #"more";
return result;
}
And call it like this:
TwoStrings twoStrs = myfunc();
NSLog(#"str1 = %#, str2 = %#", twoStrs.str1, twoStrs.str2);
You need to be careful with memory management when returning pointers even if they are wrapped inside a struct. In Objective-C the convention is that functions return autoreleased objects (unless the method name starts with create/new/alloc/copy).
You have a few options:
NSArray: Just return an array. Pretty simple.
Pointers: Pass in two pointers, and write to them instead of returning anything. Make sure to check for NULL!
Structure: Create a struct that has two fields, one for each thing you want to return, and return one of that struct.
Object: Same a structure, but create a full NSObject subclass.
NSDictionary: Similar to NSArray, but removes the need to use magic ordering of the values.
As you can only return one value/object, maybe wrap them up in an array:
-(NSArray*) arrayFromMyFunc
{
NSString *myString = #"MYDATA";
NSString *myString2 = #"MYDATA2";
return [NSArray arrayWithObjects:myString,myString2,nil];
}
You can then use it like this:
NSArray *arr = [self arrayFromMyFunc];
NSString *value1 = [arr objectAtIndex:0];
NSString *value2 = [arr objectAtIndex:1];
You could pass results back by reference, but this is easy to get wrong (syntactically, semantically, and from memory management point of view).
Edit One more thing: Make sure that you really need two return values. If they are quite independent, two separate function are often the better choice - better reusabilty and mentainable. Just in case you are making this as a matter of premature optimization. :-)
You can only directly return one value from a function. But there is a way of doing it.
-(void) myfuncWithVal1:(NSString**)val1 andVal2:(NSString**)val2
{
*val1 = #"MYDATA";
*val2 = #"MYDATA2";
}
Then to call it outside the method you'd use:
NSString* a;
NSString* b;
[self myfuncWithVal1:&a andVal2:&b];
void myfunc(NSString **string1, NSString **string2)
{
*string1 = #"MYDATA";
*string2 = #"MYDATA2";
}
...
NSString *value1, *value2;
myfunc(&value1, &value2);
Remember that you need to pass a pointer to a pointer when working with strings and other objects.
Wrap the two strings in an NSArray:
- (NSArray*)myFunc
{
NSString *myString = #"MYDATA";
NSString *myString2 = #"MYDATA2";
return [NSArray arrayWithObjects:myString, myString2, nil];
}
NSArray *theArray = [self myFunc]
NSString *value1 = [theArray objectAtIndex:0];
NSString *value2 = [theArray] objectAtIndex:1];
I see everyone has mentioned an NSArray but I'd go with an NSDictionary so the values don't have to be added in order or even at all. This means it is able to handle a situation where you only want to return the second string.
- (NSDictionary*)myFunction {
NSString *myString1 = #"string1";
NSString *myString2 = #"string2";
return [NSDictionary dictionaryWithObjectsAndKeys: myString1, #"key1", myString2, #"key2", nil];
}
NSDictionary *myDictionary = [self myFunction]
NSString *string1 = [myDictionary objectForKey:#"key1"];
NSString *string2 = [myDictionary objectForKey:#"key2"];