【问题标题】:Is there an easy way to make part of an NSString object a superscript or subscript?有没有一种简单的方法可以使 NSString 对象的一部分成为上标或下标?
【发布时间】:2010-08-19 19:22:23
【问题描述】:

例如,假设我有一个 NSString @"20O(2H,1H)19O",并且我希望所有数字都是上标。有没有简单的方法可以做到这一点?

【问题讨论】:

    标签: cocoa macos nsstring


    【解决方案1】:

    我想你可能想要NSAttributedStringNSSuperScriptAttributeName。如果您需要将其保存在NSString 中,unicode 包含superscripted digits 的字符。

    【讨论】:

    • 更新:我最终使用了 NSMutableAttributedString。不过,Apple 的文档非常需要,所以我并没有从中得到太多。我最终遵循了 Aaron Hillegass 的“Mac OS X 的 Cocoa 编程”中的示例。这实际上是一件苦差事,因为我必须跟踪我想要上标的位的确切字符位置。我所做的细节可以在 AppController.m 的源代码中找到,在方法 generateFormattedReactionString 中,来自我的项目code.google.com/p/mac-helios-sim,以防有人好奇。
    • 请注意,NSSuperscriptAttributeName 需要一个整数。这仅允许在您希望上标(或下标)为位置的位置进行相当粗略的调整。
    【解决方案2】:

    这个函数应该返回一个给定的上标数字。很简单

    -(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;   
    }
    

    给定一个输入的数字字符串,它只返回等效的上标字符串。

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 2014-12-08
      • 2010-12-08
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多