如何从 NSString 中删除第一个 space?

How to remove the first space from the NSString?

我只想删除下面字符串中的第一个 space。

NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";

Note: There is a space after IF_Distance and another space after GET_Mi. I am unable to remove the space after IF_Distance.

使用以下代码删除 space。

NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";

NSString *secondString = [str stringByReplacingOccurrencesOfString:@"IF_Distance " withString:@"IF_Distance"];

使用rangeOfString:定位第一个space,然后使用stringByReplacingCharactersInRange:withString:将其替换为空字符串。

试试这个:

NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance

str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:@"%@ ",firstStringContainingSpace]] withString:firstStringContainingSpace];

输出: str = @"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";

您可以使用以下代码先删除 space:

首先使用rangeOfString:找到space,然后使用stringByReplacingCharactersInRange:withString:方法删除。

喜欢,

NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = @" ";

NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;

if (NSNotFound != range.location) {

     strFinal = [str stringByReplacingCharactersInRange:range withString:@""];
}

如果您正在寻找更通用的方式 - 这是它的变体:

- (NSString *)removeWhitespaces:(NSString *)string {

    NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
    NSString * fStringComponent = [stringComponents firstObject];
    [stringComponents removeObject:fStringComponent];

    return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:@" "]];
}