user1960279
user1960279

Reputation: 514

How to print the reverse of NSString in objective c without using componentsSeparatedByString method?

I want to make a method which gives reverse of string.suppose I pass a NSString "Welcome to Objective C" in method and that method return a reverse of string like "C Objective to Welcome" not "C evitcejbO ot emocleW" without the use of componentsSeparatedByString method. Is it possible to do with Objective c..? Please help.

Upvotes: 1

Views: 6572

Answers (6)

Jaywant Khedkar
Jaywant Khedkar

Reputation: 6121

Try This , It's working perfect as per your expectation ,

Call Function :-

 [self reversedString:@"iOS"];

Revers String Function :-

 -(void)reversedString :(NSString *)reversStr

 {    // reversStr is "iOS"

     NSMutableString *reversedString = [NSMutableString string];
     NSInteger charIndex = [reversStr length];
     while (charIndex > 0) {
     charIndex--;
     NSRange subStrRange = NSMakeRange(charIndex, 1);
    [reversedString appendString:[reversStr substringWithRange:subStrRange]];
  }
   NSLog(@"%@", reversedString); // outputs "SOi"
 }

Hope So this is help for some one .

Upvotes: 1

John
John

Reputation: 258

Here i have done with replacing character with minimal number of looping. log(n/2).

NSString  *string=@"Happy World";
NSInteger lenth=[string length];
NSInteger halfLength=[string length]/2;

for(int i=0;i<halfLength;i++)
{
   NSString *leftString=[NSString stringWithFormat:@"%c",[string characterAtIndex:i]];
   NSString *rightString=[NSString stringWithFormat:@"%c",[string characterAtIndex:(lenth-i-1)]];

   string= [string stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:rightString];
   string=[string stringByReplacingCharactersInRange:NSMakeRange((lenth-i-1), 1) withString:leftString];

}

NSLog(@"%@",string);

Upvotes: 1

Gagan_iOS
Gagan_iOS

Reputation: 4060

I used below method for reversing string in iOS

- (NSString *)reverseString:(NSString *)stringToReverse
{
    NSMutableString *reversedString = [NSMutableString stringWithCapacity:[stringToReverse length]];
    [stringToReverse enumerateSubstringsInRange:NSMakeRange(0, [stringToReverse length])
                                        options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)
                                     usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
            [reversedString appendString:substring];
    }];
    return reversedString;
}

Upvotes: 2

Fogmeister
Fogmeister

Reputation: 77641

You can enumerate strings by words.

NSString *string = @"Welcome to Objective-C!";

NSMutableArray *words = [NSMutableArray array];

[string enumerateLinguisticTagsInRange:NSMakeRange(0, [string length])
                                scheme:NSLinguisticTagSchemeTokenType
                               options:0
                           orthography:nil
                            usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
                                [array addObject:[string substringWithRange:tokenRange]];
                            }];

NSMutableString *reverseString = [[NSMutableString alloc] init];

for (NSString *word in [words reverseObjectEnumerator]){
    [reverse appendString:word];
}

NSLog(@"%@", reverseString);

This will print...

"!C-Objective to Welcome"

You can change the options to omit whitespaces and stuff...

Upvotes: 6

AdamM
AdamM

Reputation: 4440

Sorry I misread your question earlier. I did it using a series of loops, my answer is messier than Fogmeister but I wanted to give it a shot to see if I could do it.

NSString *str = @"This is a test";


    NSMutableArray *array = [[NSMutableArray alloc] init];

    for(int i = 0; i < [str length]; i++)
    {
        char sTest = [str characterAtIndex:i];
        if(sTest == ' ')
        {
            [array addObject:[NSNumber numberWithInt:i]];
        }
    }

    NSInteger iNext = [[array objectAtIndex:[array count]-1] integerValue];
    iNext+=1;

    if(iNext < [str length])
    {
       [array addObject:[NSNumber numberWithInt:iNext]]; 
    }

    NSMutableArray *wordArray = [[NSMutableArray alloc] init];

    for(int i = 0; i < [array count]; i++)
    {
        if (i == 0)
        {
            int num = [[array objectAtIndex:i] integerValue];
            NSString *s = [[str substringFromIndex:0] substringToIndex:num];
            [wordArray addObject:s];

        }
        else if(i == [array count]-1)
        {
            int prev = [[array objectAtIndex:i-1] integerValue]+1;
            int num =  [str length];
            NSString *s = [[str substringToIndex:num] substringFromIndex:prev];
            [wordArray addObject:s];
        }
        else
        {
            int prev = [[array objectAtIndex:i-1] integerValue]+1;
            int num = [[array objectAtIndex:i] integerValue];

            NSString *s = [[str substringToIndex:num] substringFromIndex:prev];
            [wordArray addObject:s];
        }
    }

    NSMutableArray *reverseArray = [[NSMutableArray alloc]init];
    for(int i = [wordArray count]-1; i >= 0; i--)
    {

        [reverseArray addObject:[wordArray objectAtIndex:i]];
    }
    NSLog(@"%@", reverseArray);

Upvotes: 1

Manlio
Manlio

Reputation: 10865

There is no API to do that, if that's what you are asking.

You can always iterate through the string looking for white spaces (or punctuation, it depends on your needs), identify the words and recompose your "reversed" message manually.

Upvotes: 0

Related Questions