Files and Text Processing
Parsing a Path
Pull the name and extension out of a path string.
path-parse
A path is just text. `lastIndexOf` and `substring` split it into a file name and an extension without touching the filesystem.
Parsing a Path
PathParse.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val path = "docs/report.txt"
val slash = path.lastIndexOf("/")
val name = path.substring(slash + 1)
val dot = name.lastIndexOf(".")
val ext = if (dot >= 0) name.substring(dot + 1) else ""
println("name=" + name)
println("ext=" + ext)
}
}
object Main {
def main(args: Array[String]): Unit = {
val path = "img/logo.png"
val slash = path.lastIndexOf("/")
val name = path.substring(slash + 1)
val dot = name.lastIndexOf(".")
val ext = if (dot >= 0) name.substring(dot + 1) else ""
println("name=" + name)
println("ext=" + ext)
}
}
object Main {
def main(args: Array[String]): Unit = {
val path = "notes.md"
val slash = path.lastIndexOf("/")
val name = path.substring(slash + 1)
val dot = name.lastIndexOf(".")
val ext = if (dot >= 0) name.substring(dot + 1) else ""
println("name=" + name)
println("ext=" + ext)
}
}
path ← docs/report.txt, slash ← 4, name ← report.txt, dot ← 6
1object Main {2 def main(args: Array[String]): Unit = {3 val path→ docs/report.txt = "docs/report.txt" //@path="img/logo.png", "notes.md"4 val slash→ 4 = pathdocs/report.txt.lastIndexOf("/")5 val name→ report.txt = pathdocs/report.txt.substring(slash4 + 1)6 val dot→ 6 = namereport.txt.lastIndexOf(".")7 val ext→ txt = if (dot6 >= 0) namereport.txt.substring(dot + 1) else ""89 println("name=" + namereport.txt)10 println("ext=" + exttxt)11 }12}outputname=report.txt ext=txt
path ← img/logo.png, slash ← 3, name ← logo.png, dot ← 4, ext ← png
1object Main {2 def main(args: Array[String]): Unit = {3 val path→ img/logo.png = "img/logo.png"4 val slash→ 3 = pathimg/logo.png.lastIndexOf("/")5 val name→ logo.png = pathimg/logo.png.substring(slash3 + 1)6 val dot→ 4 = namelogo.png.lastIndexOf(".")7 val ext→ png = if (dot4 >= 0) namelogo.png.substring(dot + 1) else ""89 println("name=" + namelogo.png)10 println("ext=" + extpng)11 }12}outputname=logo.png ext=png
path ← notes.md, slash ← -1, name ← notes.md, dot ← 5, ext ← md
1object Main {2 def main(args: Array[String]): Unit = {3 val path→ notes.md = "notes.md"4 val slash→ -1 = pathnotes.md.lastIndexOf("/")5 val name→ notes.md = pathnotes.md.substring(slash-1 + 1)6 val dot→ 5 = namenotes.md.lastIndexOf(".")7 val ext→ md = if (dot5 >= 0) namenotes.md.substring(dot + 1) else ""89 println("name=" + namenotes.md)10 println("ext=" + extmd)11 }12}outputname=notes.md ext=md