Loop through an array of single character strings, find consecutive characters, extract them, and insert them in the original array as a single string

huangapple go评论69阅读模式
英文:

Loop through an array of single character strings, find consecutive characters, extract them, and insert them in the original array as a single string

问题

我理解你的问题。你需要一个方法来检测原始字符数组中的连续字符组合,并将它们替换为对应的特殊符号。你可以尝试以下的方法来实现这个功能:

func replaceConsecutiveCharacters(_ stringArray: [String]) -> [String] {
    var resultArray = [String]()
    var index = 0
    
    while index < stringArray.count {
        if index < stringArray.count - 1 {
            let currentChar = stringArray[index]
            let nextChar = stringArray[index + 1]
            
            if checkForConsecutiveCharacters(character1: currentChar, character2: nextChar) {
                resultArray.append(currentChar + nextChar)
                index += 2 // Skip the next character
            } else {
                resultArray.append(currentChar)
                index += 1
            }
        } else {
            // Last character, just add it to the result
            resultArray.append(stringArray[index])
            index += 1
        }
    }
    
    return resultArray
}

然后,你可以在 addLetter 函数中调用 replaceConsecutiveCharacters 方法,将 toBeTranslated 数组作为参数传入,以获得包含特殊符号的新数组。

这将帮助你将连续字符组合替换为对应的特殊符号,如你所需的那样。

英文:

I am creating a translator app of sorts and I am stuck on one little aspect. So far, I have a custom keyboard that creates a single string, then a function that takes that string and converts it to an array of characters:

@State var toBeTranslated = &quot;&quot;

// function added to custom keyboard buttons with corresponding characters
func addLetter(_ letter: String -&gt; [String] {
    let stringArray = toBeTranslated.map{ String($0) }
    return stringArray
}

After the string is converted into an array of characters, the array is iterated through and each index is assigned to the string name of an Image to display on screen. The images are of special symbol for that letter:

// the WrappingHStack is used as the ForEach in this case
WrappingHStack(alignment: .leading, spacing: .dynamic(minSpacing: 15)) {
                    WrappingHStack(addLetter(toBeTranslated), id: \.self) { character in
                        Image(character)
                            .resizable()
                            .scaledToFit()
                            .frame(width: 30, height: 30)
                    }
                }

The issue I have now is the special characters for the letter combinations of "CH" "AE", "EO", "KH" "NG", "OO", "SH", and "TH". Meaning, if the word(s) has these letters consecutively, a single symbol will be represented instead of two.

For instance, if the user typed in "SMOOTH CHARACTER", instead of 15 symbols, there will be 12 as the "OO", "TH", and "CH" will all be replaced with the single symbol.

I've been trying different methods to identify these consecutive characters like this function:

func checkForConsecutiveCharacters(character1: String, character2: String, within stringArray: [String]) -&gt; Bool {
        for index in stringArray.indices.dropLast() {
            if stringArray[index] == character1 &amp;&amp; stringArray[index + 1] == character2 {
                return true
            }
        }
        return false
    }

I just can't get past this part.

Basically, I need to be able to iterate through the original array of single characters, identify if the consecutive characters above exist, then I need to either combine just those two character into a single string in the original array, or extract them, then combine them, then replace them with those two characters in the original array to display the corresponding symbol image.

i.e. end result of:

convert from:
[&quot;S&quot;, &quot;M&quot;, &quot;O&quot;, &quot;O&quot;, &quot;T&quot;, &quot;H&quot;, &quot; &quot;, &quot;C&quot;, &quot;H&quot;, &quot;A&quot;, &quot;R&quot;, &quot;A&quot;, &quot;C&quot;, &quot;T&quot;, &quot;E&quot;, &quot;R&quot;]

convert to:
[&quot;S&quot;, &quot;M&quot;, &quot;OO&quot;, &quot;TH&quot;, &quot; &quot;, &quot;CH&quot;, &quot;A&quot;, &quot;R&quot;, &quot;A&quot;, &quot;C&quot;, &quot;T&quot;, &quot;E&quot;, &quot;R&quot;]

Thanks!

答案1

得分: 0

这是一个使用正则表达式检测特殊字符的解决方案。它通过索引遍历字符串。如果检测到模式,就会追加两个字符到结果中,否则只追加一个。当前索引会相应地增加。

func convert(string: String) -> [String] {
    var result = [String]()
    let specialCharacterPattern = "^(CH|AE|EO|KH|NG|OO|SH|TH)"
    var currentIndex = string.startIndex
    while currentIndex < string.endIndex {
        let isSpecial = string[currentIndex...].range(of: specialCharacterPattern, options: .regularExpression) != nil
        var temp = String(string[currentIndex])
        currentIndex = string.index(after: currentIndex)
        if isSpecial {
            temp.append(string[currentIndex])
            currentIndex = string.index(after: currentIndex)
        }
        result.append(temp)
    }
    return result
}

print(convert(string: "SMOOTH CHARACTER"))
英文:

This is a solution which detects the special characters with regular expression. It walks thru the string by index. If a pattern is detected two characters are appended to the result otherwise only one. The current index is increased accordingly.

func convert(string: String) -&gt; [String] {
    var result = [String]()
    let specialCharacterPattern = &quot;^(CH|AE|EO|KH|NG|OO|SH|TH)&quot;
    var currentIndex = string.startIndex
    while currentIndex &lt; string.endIndex {
        let isSpecial = string[currentIndex...].range(of: specialCharacterPattern, options: .regularExpression) != nil
        var temp = String(string[currentIndex])
        currentIndex = string.index(after: currentIndex)
        if isSpecial {
            temp.append(string[currentIndex])
            currentIndex = string.index(after: currentIndex)
        }
        result.append(temp)
    }
    return result
}

print(convert(string: &quot;SMOOTH CHARACTER&quot;))

huangapple
  • 本文由 发表于 2023年3月20日 22:44:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75791733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定