How to comapare the string character by character in Objective c? - iphone

Iam developing one applciation.In that i want to comapare the every character of string with other character.So please tell me how to do that one.

Use characterAtIndex: function of NSString to extract the character by index.
- (unichar)characterAtIndex:(NSUInteger)index

for (int i=0; i<[string length]; i++) {
char = [string characterAtIndex:i];
NSString *charString = [NSString stringWithFormat:#"%c", char];
if ([charString isEqualToString:comparisonString]) {
//match
}
else {
//no match
}
}

if you want to compare a string. Using isEqualToString method.
NSMutableString *str = [[NSMutableString alloc] initWithString:#"a"];
if([str isEqualToString:#"a"]){
// match
}
else{
// not match
}

Related

How to remove starting 0's in uitextfield text in iphone sdk

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

ios method to insert spaces in string

In my app I download a file from amazon's s3, which does not work unless the file name has no spaces in it. For example, one of the files is "HoleByNature". I would like to display this to the user as "Hole By Nature", even though the file name will still have no spaces in it.
I was thinking of writing a method to search through the string starting at the 1st character (not the 0th) and every time I find a capital letter I create a new string with a substring until that index with a space and a substring until the rest.
So I have two questions.
If I use NSString's characterAtIndex, how do I know if that character is capital or not?
Is there a better way to do this?
Thank you!
Works for all unicode uppercase and titlecase letters
- (NSString*) spaceUppercase:(NSString*) text {
NSCharacterSet *set = [NSCharacterSet uppercaseLetterCharacterSet];
NSMutableString *result = [NSMutableString new];
for (int i = 0; i < [text length]; i++) {
unichar c = [text characterAtIndex:i];
if ([set characterIsMember:c] && i!=0){
[result appendFormat:#" %C",c];
} else {
[result appendFormat:#"%C",c];
}
}
return result;
}
I would not go to that approach because I know you can download files with spaces try this please when you construct the NSUrl object
#"my_web_site_url\sub_domain\sub_folder\My%20File.txt
this will download "My File.txt" from the URL provided. so basically you can replace all spaces in the URL with %20
reference:
http://www.w3schools.com/tags/ref_urlencode.asp
Got it working with Jano's answer but using the isupper function as suggested by Richard J. Ross III.
- (NSString*) spaceUppercase:(NSString*) text
{
NSMutableString *result = [NSMutableString new];
[result appendFormat:#"%C",[text characterAtIndex:0]];
for (int i = 1; i < [text length]; i++)
{
unichar c = [text characterAtIndex:i];
if (isupper(c))
{
[result appendFormat:#" %C",c];
}
else
{
[result appendFormat:#"%C",c];
}
}
return result;
}

Character occurrences in a String Objective C

How can I count the occurrence of a character in a string?
Example
String: 123-456-7890
I want to find the occurrence count of "-" in given string
You can simply do it like this:
NSString *string = #"123-456-7890";
int times = [[string componentsSeparatedByString:#"-"] count]-1;
NSLog(#"Counted times: %i", times);
Output:
Counted times: 2
This will do the work,
int numberOfOccurences = [[theString componentsSeparatedByString:#"-"] count];
I did this for you. try this.
unichar findC;
int count = 0;
NSString *strr = #"123-456-7890";
for (int i = 0; i<strr.length; i++) {
findC = [strr characterAtIndex:i];
if (findC == '-'){
count++;
}
}
NSLog(#"%d",count);
int total = 0;
NSString *str = #"123-456-7890";
for(int i=0; i<[str length];i++)
{
unichar c = [str characterAtIndex:i];
if (![[NSCharacterSet alphanumericCharacterSet] characterIsMember:c])
{
NSLog(#"%c",c);
total++;
}
}
NSLog(#"%d",total);
this worked. hope it helps. happy coding :)
int num = [[[myString mutableCopy] autorelease] replaceOccurrencesOfString:#"-" withString:#"X" options:NSLiteralSearch range:NSMakeRange(0, [myString length])];
The replaceOccurrencesOfString:withString:options:range: method returns the number of replacements that were made, so we can use that to work out how many -s are in your string.
You can use replaceOccurrencesOfString:withString:options:range: method of NSString
The current selected answer will fail if the string starts or ends with the character you are checking for.
Use this instead:
int numberOfOccurances = (int)yourString.length - (int)[yourString stringByReplacingOccurrencesOfString:#"-" withString:#""].length;

NSString to NSArray

I want to split an NSString into an NSArray. For example, given:
NSString *myString=#"ABCDEF";
I want an NSArray like:
NSArray *myArray={A,B,C,D,E,F};
How to do this with Objective-C and Cocoa?
NSMutableArray *letterArray = [NSMutableArray array];
NSString *letters = #"ABCDEF𝍱क्";
[letters enumerateSubstringsInRange:NSMakeRange(0, [letters length])
options:(NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[letterArray addObject:substring];
}];
for (NSString *i in letterArray){
NSLog(#"%#",i);
}
results in
A
B
C
D
E
F
𝍱
क्
enumerateSubstringsInRange:options:usingBlock: available for iOS 4+ can enumerate a string with different styles. One is called NSStringEnumerationByComposedCharacterSequences, what will enumerate letter by letter but is sensitive to surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters, all referred as Composed Character
Note, that the accepted answer "swallows" 𝍱and breaks क् into क and ्.
Conversion
NSString * string = #"A B C D E F";
NSArray * array = [string componentsSeparatedByString:#" "];
//Notice that in this case I separated the objects by a space because that's the way they are separated in the string
Logging
NSLog(#"%#", array);
This is what the console returned
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[theString length]];
for (int i=0; i < [theString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%C", [theString characterAtIndex:i]];
[chars addObject:ichar];
}
This link contains examples to split a string into a array based on sub strings and also based on strings in a character set. I hope that post may help you.
here is the code snip
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
Without loop you can use this:
NSString *myString = #"ABCDEF";
NSMutableString *tempStr =[[NSMutableString alloc] initWithString:myString];
if([myString length] != 0)
{
NSError *error = NULL;
// declare regular expression object
NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:#"(.)" options:NSMatchingReportCompletion error:&error];
// replace each match with matches character + <space> e.g. 'A' with 'A '
[regex replaceMatchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0,[myString length]) withTemplate:#"$0 "];
// trim last <space> character
[tempStr replaceCharactersInRange:NSMakeRange([tempStr length] - 1, 1) withString:#""];
// split into array
NSArray * arr = [tempStr componentsSeparatedByString:#" "];
// print
NSLog(#"%#",arr);
}
This solution append space in front of each character with the help of regular expression and uses componentsSeparatedByString with <space> to return an array
Swift 4.2:
String to Array
let list = "Karin, Carrie, David"
let listItems = list.components(separatedBy: ", ")
Output : ["Karin", "Carrie", "David"]
Array to String
let list = ["Karin", "Carrie", "David"]
let listStr = list.joined(separator: ", ")
Output : "Karin, Carrie, David"
In Swift, this becomes very simple.
Swift 3:
myString.characters.map { String($0) }
Swift 4:
myString.map { String($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;
}