【问题标题】:Crop NSURL / NSString裁剪 NSURL / NSString
【发布时间】:2025-12-17 05:40:01
【问题描述】:

我得到了一些指向某些 mp3 的 URL 标题,例如:

(1) localhost://blablabla/song1.mp3
(2) localhost://blablabla/songwithmorechars.mp3

等等。

如何将 URL 裁剪为:

(1) song1.mp3
(2) songwithmorechars.mp3

需要在UILabel 中显示我的AVAudioPlayer 正在播放的当前歌曲。

谢谢

解决方案:

这是交易:

titleLabel.text = [[[self.audioPlayer.url absoluteString] lastPathComponent] stringByReplacingOccurrencesOfString:@".mp3" withString:@""];

【问题讨论】:

    标签: iphone xcode nsstring nsurl crop


    【解决方案1】:

    取最后一个 / 的子字符串(在 ObjC 中有一个方法!)

    NSString *sub = [url lastPathComponent];
    

    这是该方法的信息:

    NSString lastPathComponent Apple Doc

    【讨论】:

      【解决方案2】:

      使用[url lastPathComponent]即可,不需要先转换成字符串。

      【讨论】:

        【解决方案3】:

        使用

         NSString *lastString = [yourStringName lastPathComponent];
        

        【讨论】:

          【解决方案4】:
          NSURL *firstURL = [NSURL URLWithString:@"localhost://blablabla/song1.mp3"];
          NSString *firstString = [firstURL absoluteString];
          NSLog(@"Name:%@",[firstString lastPathComponent]);
          

          来自文档:

          NSURL Class Reference

          NSString Class Reference

          【讨论】: