Objective C remove end of string after certain character [duplicate] - objective-c

This question already has answers here:
Remove Characters and Everything After from String
(2 answers)
Closed 8 years ago.
I can't seem to find the answer to this anywhere. I can do it in c but objective c is difficult.
I want to cut the end of a string after a certain character
so user#example.com will become user (cut at '#')
How do I do this?

This will give you the first chunk of text that comes before your special character.
NSString *separatorString = #"#";
NSString *myString = #"user#example.com";
NSString *myNewString = [myString componentsSeparatedByString:separatorString].firstObject;
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:

You can use a combination of substringToIndex: and rangeOfString: methods, like this:
NSString *str = #"user#example.com";
NSRange pos = [str rangeOfString:#"#"];
if (pos.location != NSNotFound) {
NSString *prefix = [str substringToIndex:pos.location];
}
Notes:
You need to check the location against NSNotFound to ensure that the position is valid.
substringToIndex: excludes the index itself, so the # character would not be included.

Related

how to replace one substring with another in Objective C?

I want to replace an NSString substring with another substring in Objective C.
I know how to locate the substring I want to replace:
NSRange range = [string rangeOfString:substringIWantToReplace];
NSString *substring = [string substringFromIndex:NSMaxRange(range)];
But when it comes to actually removing/replacing it, I'm a little confused. Do I follow the C++ method at Replace substring with another substring C++? Or the C method at how to replace substring in c?? There's a related question at Objective-C: Substring and replace, but the string in question is a URL, so I don't think I can use the answers.
I think your answer is here Replace occurrences of NSString - iPhone:
[response stringByReplacingOccurrencesOfString:#"aaa" withString:#"bbb"]; defenetly works on any string and URL also.
If your concern about percent-notation of url and you want to be sure it will be replaced properly, you can firstly decode string, replace, and then encode:
// decode
NSString *path = [[#"path+with+spaces"
stringByReplacingOccurrencesOfString:#"+" withString:#" "]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// replace
path = [path stringByReplacingOccurrencesOfString:#"aaa" withString:#"bbb"]
// encode
path = CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)path,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8 );
This is how I check for a substring and replace/remove substrings from NSString:
if([titleName rangeOfString:#"""].location != NSNotFound) {
titleName = [titleName stringByReplacingOccurrencesOfString:#""" withString:#"\""];
}

Compare char array with string in iOS program [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to compare char* and NSString?
If I have:
char XYZ[256]="";
how can I compare this char array with another string (e.g. "testing") in an iOS Objective-C program?
Use strcmp
char XYZ[256] = "";
char *string = "some other string";
int order = strcmp(XYZ, string);
RETURN VALUES
The strcmp() and strncmp() functions return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters, so that \200' is greater than\0'.
You can also convert them up to NSString, this makes a lot overhead, but brings your string to Objective-C object:
char XYZ[256] = "";
NSString *s = [[NSString alloc] initWithBytes:XYZ length:strlen(XYZ) encoding:[NSString defaultCStringEncoding]];
NSString *testing = #"testing";
if ([testing compare:s] == NSOrderedSame) {
NSLog(#"They are hte same!");
}
Note that strcmp is A LOT faster!
Just because it is iOS doesnt mean that you cannot "#include" string.h and use "strcmp" (now as stated above).
The alternative would be to create a new NSString and compare it using a comperable iOS Objective-C call:
NSString myString = [NSString stringWithCString:XYZ encodingNSASCIIStringEncoding];
if(YES == [myString isEqualToString:#"testing"]){
// Perform Code if the strings are equal
}else{
// Perform Code if the strings are NOT equal
}

How to get the substring of a string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to get substring of nsstring?
how do I get a substring in iOS?
I am new to iphone.In my project i have a string such as chapter1 but actually i want the substring 1 only how it is possible.if any body know this please help me
Check out the substringFromIndex: or substringToIndex: methods of NSString. You can find the documentation for NSString here.
Ex:
NSString *string = #"Chapter1";
NSString *newString = [string subStringFromIndex: ([string length] - 1)]; // => "1"

How to remove certain sets of punctuation bet retain others in a string?

I'm creating a URL from various parts in order to make a phone call using
NSURL* url = [NSURL URLWithString:[kCallURLBase stringByAppendingString:numberStr]];
[[UIApplication sharedApplication] openURL:url];
// kCallURLBase is "tel:"
If numberStr contains '(' or ')' then url is null, and from reading other postings on here people have been having difficulty if the number contains spaces or '-' etc. So I added the following:
NSMutableCharacterSet *charSet = [[NSMutableCharacterSet alloc] init];
[charSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
[charSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
[charSet formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
NSArray *arrayWithNumbers = [self.number componentsSeparatedByCharactersInSet:charSet];
NSString *numberStr = [arrayWithNumbers componentsJoinedByString:#""];
However some numbers might be of the form *56 as they are being made from a handset in which case the * character needs to be retained. How can I remove all the other unnecessary characters but retain the *?
Alternatively, is there a better solution then this approach?
Create a character set using the characters you do want (digits, #, and *), then split your input string on any characters that are not in that set, and join the results back together. That will leave you with only valid characters in your string.
NSString *numberStr = #"(212) 555-1212 *99";
NSCharacterSet *illegalCharSet = [[NSCharacterSet characterSetWithCharactersInString:#"1234567890*#"] invertedSet];
NSString *convertedStr = [[numberStr componentsSeparatedByCharactersInSet:illegalCharSet] componentsJoinedByString:#""];
// convertedStr => 2125551212*99
Actually, I think that instead of filtering out disallowed characters, it'd be better to just take the good ones. Those would basically be: digits, *, #. So you could just iterate through the string, and collect characters representing digits, *, # in an array, and then join components of this array.
Probably the easy way to iterate over the string is to use something like:
const char *the_string = [numberString UTF8String];
Then just iterate from the_string[0] to the_string[ strlen(the_string) - 1 ].
And you could fairly easy test for digits either using isdigit(the_string[i]) from ctype.h, or doing if (the_string[i] >= '0' && the_string[i] <= '9').

how to get first three characters of an NSString?

How can I return the first three characters of an NSString?
mystr=[mystr substringToIndex:3];
Be sure your string has atleast 3 ch.. o.e. it will crash the app.
Here are some other links to check NSsting operations...
Link1
Link2
Apple Link
First, you have to make sure that the string contains at least 3 characters:
NSString *fullString = /* obtain from somewhere */;
NSString *prefix = nil;
if ([fullString length] >= 3)
prefix = [fullString substringToIndex:3];
else
prefix = fullString;
substringToIndex: will throw an exception if the index you provide is beyond the end of the string.
the right way is:
text = [text substringToIndex:NSMaxRange([text rangeOfComposedCharacterSequenceAtIndex:2])];
substringToIndex of NSString is indexing by code unit, emoji takes two code units.
make sure check the index yourself.