首页 > 解决方案 > 如何截断歌曲名称中的 .wav 和下划线

问题描述

我有一个可以正常工作的歌曲播放器,但我不知道如何将 .wav 去掉结尾,并将下划线从歌曲名称中去掉。当我的音乐播放器不工作时,那是因为没有下划线。如果不更改歌曲文件名,我将如何做到这一点。

Secure_The_Bag.wav to Secure The Bag

我认为这段代码会做到这一点,但事实并非如此。

 var name = String()

func getName() -> String {
      return name
  }

专辑歌曲视图控制器:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "SongsTableViewCell", for: indexPath) as! SongsTableViewCell
    cell.mainLabel.text = song[indexPath.row].getName()
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let songName = song[indexPath.row].getName()
    let fileURLString = "\(filePath)\(songName)"
    print(fileURLString)
    Player.shared.playStream(fileUrl: fileURLString)

}

标签: iosswift

解决方案


有很多方法可以实现您想要的结果。最简单/直接的方法之一是使用该replacingOccurences方法。

var name = "Secure_The_Bag.wav"

name = name.replacingOccurrences(of: ".wav", with: "")
// name is now "Secure_The_Bag"

name = name.replacingOccurrences(of: "_", with: " ")
// name is now "Secure The Bag"

推荐阅读