【问题标题】:How to substract string correctly?如何正确减去字符串?
【发布时间】:2012-08-29 16:58:27
【问题描述】:

我在两个对象中有两个字符串:

<div align="center"><img src="http://farm9.staticflickr.com/8448/7882675644_76605a2a3d_b.jpg" border="0" alt="" /></div><

<img src="http://farm9.staticflickr.com/8425/7881940452_d2a8e898a3_o.png" border="0" alt="" /><br /><

我正在尝试减去图像的链接。

我使用对象方法获取链接:

NSMutableString *string = [NSMutableString stringWithString:description];

int left = [string rangeOfString:@"http://"].location;

int right = 0;

if ([string rangeOfString:@".jpg"].location != NSNotFound) {
    right = [string rangeOfString:@".jpg"].location;
}
else if ([string rangeOfString:@".png"].location != NSNotFound){
    right = [string rangeOfString:@".png"].location;
}


NSString *sub = [string substringWithRange:NSMakeRange(left, right)];

NSLog(@"%@",sub);

但问题是当我打印我减去的内容时:

2012-08-29 18:53:30.716 MyApple[56335:c07] http://farm9.staticflickr.com/8448/7882675644_76605a2a3d_b.jpg" border="0" alt="" /></di
2012-08-29 18:53:30.717 MyApple[56335:c07] http://farm9.staticflickr.com/8425/7881940452_d2a8e898a3_o.png" bord

IMO 我从 http:// 减去 .jpg 或 .png,但它无法正常工作。

感谢您的帮助。

【问题讨论】:

    标签: objective-c nsstring substring nsrange


    【解决方案1】:

    NSMakeRange()的第二个参数是长度,所以你可能需要

    NSString *sub = [string substringWithRange:NSMakeRange(left, right - left)];
    

    你也应该看看NSRegularExpression

    【讨论】:

    • @TomaszSzulc:是的,这只是一个经常发生的小错误。 - 但无论如何你都应该“接受”答案,以便将问题从“未回答”列表中删除。
    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多