如何在获得结果之前拆分和删除空格

时间:2016-08-09 14:24:14

标签: scala split

我有String

val str = "9617 / 20634"

因此,在分割之后,我只想解析2个值9617 & 20634以计算百分比。 因此,我可以在拆分之后代替trim吗?

2 个答案:

答案 0 :(得分:1)

拆分后删除空格比以前更容易。除非你以前想要修剪它,否则这是一种更简单的方法。

Try
    Success = True
    Dim EM As New EmailMessage(service)
    Dim Names as String()
    'To
    Names = EmailTo.Split(";")
    For Each S as String in Names
        If S <> "" Then EM.ToRecipients.Add(S)
    Next
    'CC
    Names = EmailCC.Split(";")
    For Each S as String in Names
        If S <> "" Then EM.CcRecipients.Add(S)
    Next
    'Bcc
    Names = EmailBCC.Split(";")
    For Each S as String in Names
        If S <> "" Then EM.BccRecipients.Add(S)
    Next
    'Subject
    EM.Subject = EmailSubject
    'Body
    EM.Body = EmailBody
    'Attachments
    If AttachmentPath <> "" Then
        'Split attachment paths using pipe character
        Names = AttachmentPath.Split("|")
        For Each S as String in Names
            If S <> "" Then EM.Attachments.AddFileAttachment(S)
        Next
    End If
    'Voting Options
    'Save
    EM.Save(FolderToSaveIn)
Catch ex as Exception
    Success = False
    ErrorMessage = ex.ToString()
End Try

将值转换为val Array(x, y) = "9617 / 20634".split("/").map(_.trim.toFloat) val p = x / y * 100 以防止整数除法导致0。 Float语句只是另一种调用方式 Array对象的unapplySeq

答案 1 :(得分:-1)

对于可扩展的解决方案,可以使用正则表达式:

scala> val r = """(\d+) */ *(\d+)""".r
r: scala.util.matching.Regex = (\d+) +/ +(\d+)

scala> "111      / 222" match { 
  case r(a, b) => println(s"Got $a, $b")
  case _ =>  
}
Got 111, 222

如果您需要不同的使用模式,这非常有用。

您可以在此处定义输入的变量(111222)与匹配组((\d+)(\d+))之间的对应关系。