How to get a single NSString character from an NSString

前端 未结 4 1548
庸人自扰
庸人自扰 2021-01-30 15:56

I want to get a character from somewhere inside an NSString. I want the result to be an NSString.

This is the code I use to get a single character at index it:



        
相关标签:
4条回答
  • 2021-01-30 16:27

    If you just want to get one character from an a NSString, you can try this.

    - (unichar)characterAtIndex:(NSUInteger)index;
    

    Used like so:

    NSString *originalString = @"hello";
    int index = 2;
    NSString *theCharacter = [NSString stringWithFormat:@"%c", [originalString characterAtIndex:index-1]];
    //returns "e".
    
    0 讨论(0)
  • 2021-01-30 16:29

    Your suggestion only works for simple characters like ASCII. NSStrings store unicode and if your character is several unichars long then you could end up with gibberish. Use

    - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
    

    if you want to determine how many unichars your character is. I use this to step through my strings to determine where the character borders occur.

    Being fully unicode able is a bit of work but depends on what languages you use. I see a lot of asian text so most characters spill over from one space and so it's work that I need to do.

    0 讨论(0)
  • 2021-01-30 16:33

    This will also retrieve a character at index i as an NSString, and you're only using an NSRange struct rather than an extra NSString.

    NSString * newString = [s substringWithRange:NSMakeRange(i, 1)];
    
    0 讨论(0)
  • 2021-01-30 16:37
    NSMutableString *myString=[NSMutableString stringWithFormat:@"Malayalam"];
    NSMutableString *revString=@"";
    
    for (int i=0; i<myString.length; i++) {
        revString=[NSMutableString stringWithFormat:@"%c%@",[myString characterAtIndex:i],revString];
    }
    NSLog(@"%@",revString);
    
    0 讨论(0)
提交回复
热议问题