2

For example, suppose I have an NSString @"20O(2H,1H)19O", and I want all the numbers to be superscript. Is there an easy way to do this?

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
PTTHomps
  • 1,477
  • 2
  • 22
  • 38

2 Answers2

5

I think you probably want NSAttributedString with NSSuperScriptAttributeName. If you need to keep it in an NSString, unicode has characters for superscripted digits.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • UPDATE: I ended up using an NSMutableAttributedString. Apple's documentations is quite wanting, though, so I didn't get much out of it. I ended up following the examples in Aaron Hillegass's "Cocoa Programming For Mac OS X". It was actually quite a chore, as I had to keep track of the exact character positions of the bits that I wanted to superscript. Details of what I did can be found in the source code for AppController.m, in the method generateFormattedReactionString, from my project at http://code.google.com/p/mac-helios-sim/, in case anyone is curious. – PTTHomps Sep 03 '10 at 18:32
  • Note that `NSSuperscriptAttributeName` takes an integer, though. This allows only for pretty coarse adjustments where you want the superscript (or subscript) be positions. – Jay Nov 23 '12 at 13:47
3

This function should return a given number in superscript. Very simple

-(NSString *)superScriptOf:(NSString *)inputNumber{

    NSString *outp=@"";
    for (int i =0; i<[inputNumber length]; i++) {
    unichar chara=[inputNumber characterAtIndex:i] ;
    switch (chara) {
        case '1':
            NSLog(@"1");
            outp=[outp stringByAppendingFormat:@"\u00B9"];
            break;
        case '2':
            NSLog(@"2");
            outp=[outp stringByAppendingFormat:@"\u00B2"];
            break;
        case '3':
            NSLog(@"3");
            outp=[outp stringByAppendingFormat:@"\u00B3"];
            break;
        case '4':
            NSLog(@"4");
            outp=[outp stringByAppendingFormat:@"\u2074"];
            break;
        case '5':
            NSLog(@"5");
                            outp=[outp stringByAppendingFormat:@"\u2075"];
            break;
        case '6':
            NSLog(@"6");
                            outp=[outp stringByAppendingFormat:@"\u2076"];
            break;
        case '7':
            NSLog(@"7");
            outp=[outp stringByAppendingFormat:@"\u2077"];
            break;
        case '8':
            NSLog(@"8");
            outp=[outp stringByAppendingFormat:@"\u2078"];
            break;
        case '9':
            NSLog(@"9");
            outp=[outp stringByAppendingFormat:@"\u2079"];
            break;
        case '0':
            NSLog(@"0");
            outp=[outp stringByAppendingFormat:@"\u2070"];
            break;
        default:
            break;
    }
}
return outp;   
}

Given an input string of numbers it just returns the equivalent superscript string.

Tawfiqh
  • 143
  • 1
  • 10