Search code examples
objective-cnsstringnsattributedstring

How to remove \t from NSMutableAttributedString?


I have NSMutableAttributedString whose string contains tabs. I want to remove it

Sample NSstring

Hello text
    •   Text1
    •   Text2
    •   Text3

I tried the below code but it doesn't work as expected.

NSMutableAttributedString *displayText;
NSCharacterSet *charSet = [NSCharacterSet whitespaceCharacterSet];
NSRange range           = [displayText.string rangeOfCharacterFromSet:charSet];

while (range.length != 0 && NSMaxRange(range) == displayText.length)
{
    [displayText replaceCharactersInRange:range withString:@""];
    range = [displayText.string rangeOfCharacterFromSet:charSet];
}

// Trim trailing whitespace and newlines.
range = [displayText.string rangeOfCharacterFromSet:charSet options:NSBackwardsSearch];
while (range.length != 0 && NSMaxRange(range) == displayText.length)
{
    [displayText replaceCharactersInRange:range withString:EMPTY_STRING];
    range = [displayText.string rangeOfCharacterFromSet:charSet options:NSBackwardsSearch];
}

The output I am getting is

Hellotext
•Text1
•Text2
•Text3

Actual output should be like

Hello text
 • Text1
 • Text2
 • Text3

Can someone help me out on this? Thanks in advance.


Solution

  • The +whitespaceCharacterSet includes spaces as well as tabs. If you only want to match tabs, create a custom set:

    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"\t"];