What's the best way to iterate NSString? Code like following:
int len = str.length;
for (int i = 0; i < len; ++i)
{
unichar c = [str characterAtIndex:i];
// do something with c
}
looks ugly for me. I'd prefer something like
// does not compile, unfortunately
for (unichar c in str)
{
// do something with c
}
Is there any way to write it more gracefully than my first code snippet?
for(NSString *subString in yourString){
NSLog("The Substring is: %#", subString);
// do anything you want with the substring in this loop
}
This must work(if not, you can define your string as NSDictionary and try again)
Related
How can I validate password for sequential value?
Eg -
if user enters 1326 or "axdf" in password then it is valid.
if use enter 1234 or "abcd" the it is invalid.
I think you can do it this way
NSString *list= #"abcdefghijklmnopqrstuvwxyz";
NSString *password= #"abz"; // Suppose this is your password
NSRange range = [list rangeOfString:password options:NSCaseInsensitiveSearch];
if (range.location == NSNotFound) {
/* Could NOT find password in list, then it is valid */
}
else {
/* Found the password in the list then it is not valid */
}
Similarly you can do it for numbers as well
the easiest way is to use strpos.
$haystack = '01234567890';
function testConsecutive($pHaystack, $pNeedle){
return strpos($pHaystack,$pNeedle) === false?false:true;
}
Oops, I thought that I was answering php code, because that was my filter. This is not php, sorry for that.
In this case, i would suggest you to try matching ASCII value of each character in the string. If the string is sequential, ASCII value of that character should increase by 1
Here is a rough idea how you can implement it, havent tested it but hope it might be helpful.
int prevAsciiCode;
NSString *string = #"12345";
for (int i = 0; i<string.length; i++) {
int asciiCode = [string characterAtIndex:i];
if (asciiCode == prevAsciiCode+1) {
NSLog(#"String invalid");
return;
}
prevAsciiCode = asciiCode;
}
A string is a sequence of chars, each char is represented by is ASCII code, so you can iterate throw the chars of the string and compare each one with its previous int value, for example:
- (BOOL)isSequence:(NSString *)string
{
char previousChar = [string characterAtIndex:0];
int wordLength = [string length];
BOOL isSequence = YES;
for (int i = 0; i < wordLength && isSequence; i++)
{
char currentChar = [string characterAtIndex:i];
if (currentChar != previousChar+1) {
isSequence = NO;
}
previousChar = currentChar;
}
return isSequence;
}
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;
}
Please let me preface this question with an apology. I am very new to Objective C. Unfortunately, I have a very tight timeline on a project for work and need to get up to speed as fast as possible.
The code below works. I am just wondering if there is a better way to handle this... Maybe something more Cocoa-ish. The entire purpose of the function is to get an ordered list of positions in a string that have a certain value.
I fell back on a standard array for comfort reasons. The NSMutableString that I initially declare is only for testing purposes. Being a complete noob to this language and still wrapping my head around the way Objective C (and C++ I guess) handles variables and pointers, any and all hints, tips, pointers would be appreciated.
NSMutableString *mut = [[NSMutableString alloc] initWithString:#"This is a test of the emergency broadcast system. This is only a test."];
NSMutableArray *tList = [NSMutableArray arrayWithArray:[mut componentsSeparatedByString:#" "]];
int dump[(tList.count-1)];
int dpCount=0;
NSUInteger length = [mut length];
NSRange myRange = NSMakeRange(0, length);
while (myRange.location != NSNotFound) {
myRange = [mut rangeOfString:#" " options: 0 range:myRange];
if (myRange.location != NSNotFound) {
dump[dpCount]=myRange.location;
++dpCount;
myRange = NSMakeRange((myRange.location+myRange.length), (length - (myRange.location+myRange.length)));
}
}
for (int i=0; i < dpCount; ++i) {
//Going to do something with these values in the future... they MUST be in order.
NSLog(#"Dumping positions in order: %i",dump[i]);
}
text2.text = mut;
[mut release];
Thanks again for any replies.
There is not great way to do what you are trying to do. Here is one way:
// locations will be an NSArray of NSNumbers --
// each NSNumber containing one location of the substring):
NSMutableArray *locations = [NSMutableArray new];
NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length) {
searchRange.length = string.length-searchRange.location;
foundRange = [string rangeOfString:substring options:nil range:searchRange];
if(foundRange.location == NSNotFound) break;
[locations addObject:[NSNumber numberWithInt:searchRange.location]];
searchRange.location = foundRange.location+foundRange.length;
}
This might be a little more streamlined (and faster in terms of execution time, if that matters):
const char *p = "This is a test of the emergency broadcast system. This is only a test.";
NSMutableArray *positions = [NSMutableArray array];
for (int i = 0; *p; p++, i++)
{
if (*p == ' ') {
[positions addObject:[NSNumber numberWithInt:i]];
}
}
for (int j = 0; j < [positions count]; j++) {
NSLog(#"position %d: %#", j + 1, [positions objectAtIndex:j]);
}
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;
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
}