Reputation: 333
I am new to objective C and I am in a position where I need to create an iPhone App Really quickly , I am using XCode 4.2
I have a string (assuming the string is called string1) of type NSString and I would like to copy som charaters from this string into another NSString (called string2) I would like to do the following algorithm
If ( string1.char 1 ='a' and string1.char 2 ='b' and string1.char3='c')
{
string2.char1=string1.char4
string2.char2=string1.char5
string2.char3=string1.char6
}
I am not saying that the above code is executable , but this is the idea I would like to implement
also , do I need to add other framwork , synthestize any variable ? as I mentioned I am very new to all this
Thanks alot!
Upvotes: 1
Views: 699
Reputation: 1767
if ([[string1 substringWithRange:(NSRange){0, 3}] isEqualToString @"abc"]){
string2 = [string1 substringWithRange:(NSRange){0, 3}];
}
where: (NSRange){startingIndex, length}
This is using the format you mentioned in your question.
Upvotes: 1
Reputation: 8855
First off, looking at Apple's documentation is always a good idea. Just google 'NSString Class Reference.'
Second, NSString has a few methods that do what you desire, one being
[string1 characterAtIndex:myIndex];
where 'myIndex' is an NSUInteger (basically an int) of your index of interest.
With that method, you can specify an index of the string (remember, these start at 0, not 1), and check what character resides there.
if([string1 characterAtIndex:0] == 'a') {
//do something
}
Also, you can use
[string1 substringToIndex:myIndex];
to create a substring (smaller version of the original string, which would be string1) that is made up of the characters in string1 starting from index 0 (first character) and going to the index you specify.
The method
[string1 substringFromIndex:myIndex];
works similarly, but creates a substring starting at the given index and moving to the end of the string.
Also, it is important to note that strings created with the above to methods, for example:
NSString* stringTwo = [string1 substringToIndex:5];
are autoreleased, which means that the string referenced by the variable 'string1' can and will soon be wiped from memory unless you reserve the rights to use it by claiming ownership of it. The way you reserve rights to an object by claiming ownership of it (officially known as 'retaining' the object) is by calling
[string1 retain];
Now you own that object, and Objective C promises not to free that memory until you release ownership of it using
[string1 release];
Upvotes: 5