You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#实现英文单词音节拆分至列表的新手求助

Unity C# 英文单词音节拆分实现(新手向)

我是编程新手,目前在Unity中使用C#开发,需要将英文单词/名字的每个音节拆分存入列表。现有代码能完美统计音节数量,但无法实现音节拆分功能。使用输入框获取单词,当前示例单词为“johnathon”,期望输出格式类似{"joh", "nat", "hon"}。

修改后的完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;

public class SyllableSeperator : MonoBehaviour
{
    string word = "johnathon";

    private void Start()
    {
        // 调用拆分方法并输出结果
        List<string> syllables = SplitIntoSyllables(word);
        Debug.Log("拆分结果: " + string.Join(", ", syllables));
        
        // 同步获取音节数量
        int syllableCount = syllables.Count;
        Debug.Log("音节数量: " + syllableCount);
    }

    // 拆分单词为音节列表的方法
    public static List<string> SplitIntoSyllables(string word)
    {
        List<string> syllables = new List<string>();
        if (string.IsNullOrEmpty(word))
            return syllables;

        word = word.ToLower().Trim();
        string vowels = "aeiouy";
        bool lastWasVowel = false;
        StringBuilder currentSyllable = new StringBuilder();

        foreach (char c in word)
        {
            bool isVowel = vowels.Contains(c);
            
            // 遇到新元音组的起始,拆分出前一个音节
            if (isVowel && !lastWasVowel)
            {
                if (currentSyllable.Length > 0)
                {
                    syllables.Add(currentSyllable.ToString());
                    currentSyllable.Clear();
                }
                lastWasVowel = true;
            }

            // 拼接当前字符到正在构建的音节
            currentSyllable.Append(c);
            lastWasVowel = isVowel;
        }

        // 添加最后一个未完成的音节
        if (currentSyllable.Length > 0)
        {
            syllables.Add(currentSyllable.ToString());
        }

        // 处理结尾特殊规则:e/es/ed不算独立音节(除le结尾)
        if ((word.EndsWith("e") || word.EndsWith("es") || word.EndsWith("ed")) && !word.EndsWith("le"))
        {
            if (syllables.Count > 1)
            {
                string lastSyllable = syllables[syllables.Count - 1];
                // 将后缀合并到前一个音节
                syllables[syllables.Count - 2] += lastSyllable;
                syllables.RemoveAt(syllables.Count - 1);
            }
        }

        return syllables;
    }
}

关键逻辑说明

  • 元音组识别:沿用原代码规则,连续元音视为一个音节组,遍历过程中记录当前是否处于元音组内。
  • 音节拆分逻辑:
    • 用StringBuilder持续拼接当前音节的字符,避免频繁字符串拼接的性能损耗;
    • 遇到新元音组起始时,将已拼接的字符存入列表,开始构建新音节;
    • 遍历结束后,把最后一段字符加入列表,确保没有遗漏。
  • 结尾规则适配:对应原代码中e/es/ed不计入音节的逻辑,将这些后缀合并到前一个音节,保证拆分结果和音节数量统计一致。
  • 新手防护:增加空值判断,避免空单词导致的运行报错。

测试效果

输入johnathon时,输出结果为joh, nat, hon,符合预期;输入cake时,拆分结果为cak;输入running时,拆分结果为run, ning。

内容的提问来源于stack exchange,提问作者newguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:00:58