Scala如何拆分字符串并存储到数组中?

时间:2017-02-28 07:48:56

标签: arrays string scala

我目前正在编写一个程序,读取类似" 2 + 2"的字符串。它应该按空格分割并存储到数组中,如Array(2,+,2)。但是,我不确定如何在一个方法中执行它(因为我通常在Scala解释器中工作),在我拆分后访问结果。我知道在java中,你可以做String [] arr = string.split(" \ s +")。

def eval(s: String): Double = {
var result = 0;
s.split("\\s+");
//how do i retrieve the element that was split?
// I am trying to retrieve, like the above example, the 2 and 2
// perform an addition on them so the method will return a double
result;
}      

2 个答案:

答案 0 :(得分:1)

拆分与java相同,你可以read the answers here

您唯一缺少的就是访问使用array(index)

完成的数组
def eval(s: String): Double = {
  val operands = s.split("\\s+")
  operands(0).toDouble + operands(2).toDouble //the last statement is return statement
}

assert(eval("2 + 2") == 4)

即使您执行eval("2 - 2") == 4

,上述内容也会始终添加

但是,如果您想要完成所有操作(+-),请在operator1进行def eval(s: String): Double = { val operandsWithOperator = s.split("\\s+") operandsWithOperator(1) match { case "+" => operandsWithOperator(0).toDouble + operandsWithOperator(2).toDouble case "-" => operandsWithOperator(0).toDouble - operandsWithOperator(2).toDouble case "*" => operandsWithOperator(0).toDouble * operandsWithOperator(2).toDouble case "/" => operandsWithOperator(0).toDouble / operandsWithOperator(2).toDouble } } assert(eval("2 + 2") == 4) assert(eval("2 - 2") == 0) assert(eval("2 * 3") == 6) assert(eval("2 / 2") == 1) 索引public class EncryptationAwarePropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { private static final Logger logger = LoggerFactory.getLogger(EncryptationAwarePropertyPlaceholderConfigurer.class); @Override protected String convertPropertyValue(String originalValue) { if (originalValue.contains("{<ENC>}") && originalValue.contains("{</ENC>}")) { String encryptedTaggedValue = originalValue.substring(originalValue.indexOf("{<ENC>}"), originalValue.indexOf("{</ENC>}") + 8); String encryptedValue = originalValue.substring(originalValue.indexOf("{<ENC>}") + 7, originalValue.indexOf("{</ENC>}")); try { String decryptedValue = EncrypDecriptUtil.decrypt(encryptedValue);//EncrypDecriptUtil is my class for encription and decryption originalValue = originalValue.replace(encryptedTaggedValue, decryptedValue); } catch (GeneralSecurityException e) { logger.error("failed to decrypt property returning original value as in properties file.", e); } } return originalValue; } }

    mail.imap.task.url=imap://username:{<ENC>}encryptedPassword{</ENC>}@imap.googlemail.com:993/inbox

如果你想要两个以上的操作数,那么递归。

答案 1 :(得分:0)

使用模式匹配来提取字符串项,并匹配运算符

def eval(s: String): Double = {
  val Array(left, op, right, _*) = s.split("\\s+")
  (left.toDouble, op, right.toDouble) match {
    case (a, "+", b) => a+b
    case _           => Double.NaN  // error value
  }
}