简体   繁体   English

确定一个字符串有多少个整数,双精度数,数学运算符

[英]Determine how many Ints, Doubles, math operators a string has

I've got a problem: I'm trying to determine how many Ints and Doubles a string has, for example: 我遇到了一个问题:我正在尝试确定一个字符串有多少个Ints和Doubles,例如:

12.5+45-(67.78)*3

Expected Results: 预期成绩:

2 Ints: 45, 3

2 Doubles: 12.5, 67.78

7 symbols: .,+,-,(,.,),*

How do I determine this? 我该如何确定?
Thanks in advance. 提前致谢。 I'm totally new to Swift 我是Swift的新手

NSRegularExpression can search for everything in string. NSRegularExpression可以搜索字符串中的所有内容。 This is an example to get number from string: 这是一个从字符串获取数字的示例:

Swift extract regex matches Swift提取正则表达式匹配

You can use this regex string to get Float number: "\\d+\\.\\d+" or this to get Int number: "\\\\d+" 您可以使用此正则表达式字符串获取浮点数: "\\d+\\.\\d+"也可以获取浮点数: "\\\\d+"

let math = "+-/*()"
let teststring = "10+12.44/(3.14*7+20)"

let isOperator = { c in
    math.characters.contains(c)
}


let numbers = teststring.characters.split(whereSeparator: isOperator).map(String.init)
let operators = teststring.characters.filter(isOperator)

let integers = numbers.flatMap { Int($0) }
let doubles = numbers.flatMap { c->Double? in
    if let i = Int(c) {
        return nil
    } else {
        return Double(c)
    }
}

print("\(operators.count) operators \(operators)")
print("\(integers.count) integers \(integers)")
print("\(doubles.count) doubles \(doubles)")

/* prints

 6 operators ["+", "/", "(", "*", "+", ")"]
 3 integers [10, 7, 20]
 2 doubles [12.44, 3.1400000000000001]

 */

I would suggest decomposing the formula in substring and placing the information in an array that allows you to access individual components. 我建议将公式分解为子字符串,然后将信息放置在允许您访问各个组件的数组中。

It will be easier to count operators, integers, numbers, etc. once you have that first level of parsing done. 一旦完成了第一级解析,对运算符,整数,数字等进行计数将变得更加容易。

Here's an example of how you could produce the parsed array: 这是如何生成解析数组的示例:

let formula = "10+12.44/(3.14*7+20)"

let operators = "+-*/()"
let operSet   = Set(operators.characters)


let flags   = formula.characters.indices
              .map{($0,operSet.contains(formula[$0]))}
              // [(String.Index,Bool)]

let starts  = zip(flags,  [(formula.startIndex,true)] + flags)
              .filter{ $0.1 || $1.1 }.map{$0.0.0}
              // [String.Index]

let parsed  = zip(starts, starts.dropFirst() + [formula.endIndex])
              .map{ (string:formula[$0..<$1], start:$0, end:$1) }
              // [(String, String.Index, String.Index)]

// parsed will contain tupples with substrings and start/end indexes
//
// .string    .start   .end
// -------    ------   ----
//   10          0       2
//   +           2       3
//   12.44       3       8
//   /           8       9
//   (           9      10
//   3.14       10      14
//   *          14      15
//   7          15      16
//   +          16      17
//   20         17      19
//   )          19      20

You can then use this array for your various needs and, as a bonus you have the .start and .end to get to each of the fomula substrings 然后,您可以使用此数组来满足您的各种需求,此外,您还可以使用.start和.end来访问每个公式子字符串

let operators = parsed.filter{operators.contains($0.string)} 

let integers = parsed.filter{Int($0.string) != nil}

let decimals = parsed.filter{$0.string.contains(".")}

The way it works is by first flagging all the string indexes that correspond to an operator (the flags variable). 它的工作方式是首先标记与运算符相对应的所有字符串索引(flags变量)。

The formula substrings will start on each operator and on any character that follows an operator (the starts variable). 公式子字符串将在每个运算符和运算符之后的任何字符(starts变量)处开始。

Once we have all the string indexes for the starting positions of the formula substrings, we only need to convert them to ranges (ie from each start to the next one) and extract the substrings into an array. 一旦拥有了公式子字符串的开始位置的所有字符串索引,我们只需要将它们转换为范围(即,从每个开始到下一个),并将子字符串提取到数组中。

I could have just placed the substrings in the array but since you'll need the positions in the formula string, I made it a tuple with the index range as well (the parsed variable). 我本可以将子字符串放在数组中,但是由于您需要公式字符串中的位置,因此我也将其与索引范围(已解析的变量)组成一个元组。

Once you have the parsed array, counting operators, integers etc. becomes a simple matter of filtering. 一旦拥有了解析的数组,对运算符,整数等进行计数就成为了简单的过滤问题。

Note that this will only work for single character operators. 请注意,这仅适用于单字符运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM