Skip to content

July 18, 2014

Example: Implement a Stack of Strings in Objective C

by noise

In the next example it is shown how to implement a class of strings using Objective C language. We will first read a text from a file and we will store it into a NSString. Then we will split the string into words (by spaces) and we will store the words in a NSArray.

Then we will iterate through that NSArray will add elements to our stack only if element not equal with “-”. If element is equal with “-” character then we will pop element from top of stack. We will display elements that we remove (using pop()) from our stack.

We will also use another class called Element for elements of our stack.

Element Class

Class’s Element header file (Element.h):

#import <Foundation/Foundation.h>
 
@interface Element : NSObject
    @property NSString *value;
    @property Element *next;
@end

Class’s Element implementation file (Element.m):

#import "Element.h"
@implementation Element
@end

StackOfStrings Class

Class’s StackOfStrings header file (StackOfStrings.h):

#import <Foundation/Foundation.h>
 
@interface StackOfStrings : NSObject
-(BOOL)isEmpty;
-(void)push:(NSString *)val;
-(NSString *)pop;
@end

Class’s StackOfStrings implementation file (StackOfStrings.m):

#import "StackOfStrings.h"
#import "Element.h"
 
@interface StackOfStrings()
@property Element *topElement;
@end
 
@implementation StackOfStrings
-(BOOL)isEmpty {
    return _topElement == nil;
}
 
-(void)push:(NSString *)val {
    Element *oldTopElement = _topElement;
    _topElement = [[Element alloc] init];
    _topElement.value = val;
    _topElement.next = oldTopElement;
}
 
-(NSString *)pop {
    NSString *val = _topElement.value;
    _topElement = _topElement.next;
    return val;
}
@end

Main Program

Main program follows (main.m):

#if __has_feature(objc_arc)
    #define MyNSLog(format, ...) CFShow((__bridge CFStringRef)[NSString stringWithFormat:format, ## __VA_ARGS__]);
#else
    #define MyNSLog(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);
#endif
 
#import <Foundation/Foundation.h>
#import "StackOfStrings.h"
 
int main(int argc, const char * argv[]) {
    @autoreleasepool {
 
        NSString *fileName = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
        NSError *fileError;
        NSString *fileBuffer = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:&fileError];
 
        if (fileError)
            NSLog(@"Error opening file for read: %@", fileError.localizedDescription);
 
        NSCharacterSet *separator = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSArray *arrayOfStrings = [fileBuffer componentsSeparatedByCharactersInSet:separator];
        arrayOfStrings = [arrayOfStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self <> ''"]];
 
        StackOfStrings *stack = [[StackOfStrings alloc]init];
 
        for (NSString *word in arrayOfStrings) {
            if ([word isEqualTo:@"-"]) {
                MyNSLog(@"%@", stack.pop);
            }
            else
                [stack push:word];
        }
 
        MyNSLog(@"is empty:%d", stack.isEmpty);
    }
    return 0;
}

You will also need to create test.txt file with the following content:

the brown fox jumped - over the lazy dog - -
Read more from Objective C Examples

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments