【问题标题】:how to scramble words in sentence using C# and put in into array如何使用 C# 打乱句子中的单词并放入数组
【发布时间】:2019-03-18 10:05:01
【问题描述】:

我需要帮助从我得到的课程中修复我的代码,我尝试创建简单的脚本来打乱句子中的单词,例如“房子坏了”变成了“房子坏了”..我的代码也可以工作,但它只争一个字,就像“THE”变成了“HTE”, 我尝试使用 string.split 方法,但我不明白我必须在哪里将代码更改为数组。 这是我的代码,结果是

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

[System.Serializable]
public class Word
{
    public string word;

    [Header("biarkan kosong untuk acak otomatis")]
    public string desiredRandom;

    public string GetString()
    {
        if (!string.IsNullOrEmpty(desiredRandom))
        {
            return desiredRandom;
        }

        string result = word;

        // **I'm try to split string here where i try to input that into array**
        string[] array = result.Split(' ');
        foreach (string token in array)
        {
            Debug.Log((token).ToString());
            word = token;
        }

        result = "";

        List<char> characters = new List<char>(word.ToCharArray());
        while (characters.Count > 0)
        {
            int indexChar = Random.Range(0, characters.Count - 1);
            result += characters[indexChar];
            characters.RemoveAt(indexChar);
        }
        return result;
    }
}

public class WordScramble : MonoBehaviour
{
    public Word[] words;

    [Header("UI Reference")]
    public CharObject prefab;
    public Transform container;
    public float space;
    public float lerpSpeed = 5;

    List<CharObject> charObjects = new List<CharObject>();
    CharObject firstSelected;

    public int currentWord;
    public static WordScramble main;

    void Awake()
    {
        main = this;
    }

    // Use this for initialization
    void Start()
    {
        ShowScramble(currentWord);
    }

    // Update is called once per frame
    void Update()
    {
        RepositionObject();
    }

    void RepositionObject()
    {
        if (charObjects.Count == 0)
        {
            return;
        }

        float center = (charObjects.Count - 1) / 2;
        for (int i = 0; i < charObjects.Count; i++)
        {
            charObjects[i].rectTransform.anchoredPosition
                = Vector2.Lerp(charObjects[i].rectTransform.anchoredPosition,
                new Vector2((i - center) * space, 0), lerpSpeed * Time.deltaTime);
            charObjects[i].index = i;
        }
    }

    public void ShowScramble()
    {
        ShowScramble(Random.Range(0, words.Length - 1));
    }

    public void ShowScramble(int index)
    {
        charObjects.Clear();
        foreach (Transform child in container)
        {
            Destroy(child.gameObject);
        }

        if (index > words.Length - 1)
        {
            Debug.LogError("index out of range between 0-" + (words.Length - 1).ToString());
            return;
        }

        // string result = huruf ;

        //  foreach (string words is word());

        char[] chars = words[index].GetString().ToCharArray();

        foreach (char c in chars)
        {
            CharObject clone = Instantiate(prefab.gameObject).GetComponent<CharObject>();
            clone.transform.SetParent(container);
            charObjects.Add(clone.Init(c));
        }
        currentWord = index;
    }

    public void Swap(int indexA, int indexB)
    {
        CharObject tmpA = charObjects[indexA];
        charObjects[indexA] = charObjects[indexB];

        charObjects[indexB] = tmpA;

        charObjects[indexA].transform.SetAsLastSibling();
        charObjects[indexB].transform.SetAsLastSibling();

        CheckWord();
    }

    public void Select(CharObject charObject)
    {
        if (firstSelected)
        {
            Swap(firstSelected.index, charObject.index);

            // unselect
            //firstSelected = null;
            firstSelected.Select();
            charObject.Select();
        }
        else
        {
            firstSelected = charObject;
        }
    }

    public void UnSelect()
    {
        firstSelected = null;
    }

    public void CheckWord()
    {
        StartCoroutine(CoCheckWord());
    }

    IEnumerator CoCheckWord()
    {
        yield return new WaitForSeconds(0.5f);

        string word = "";
        foreach (CharObject charObject in charObjects)
        {
            word += charObject.character;
        }

        if (word == words[currentWord].word)
        {
            currentWord++;
            ShowScramble(currentWord);
        }
    }
}

这是一个结果

也许我可以为这个问题寻求帮助,我还在学习 C#,如果我的代码搞砸了,我很抱歉

【问题讨论】:

    标签: c# arrays unity3d scramble


    【解决方案1】:

    这是一种随机化文本中单词位置的简单方法

    var rd = new Random();
    string[] words = text.Split(' ').OrderBy(w => rd.Next()).ToArray();
    
    // If you want a simple string instead of an array of words
    string rdText = string.Join(" ", words);
    

    【讨论】:

    • 这基本上是this answer的重复。此外,OP 明确需要输出是一个数组而不是一个新字符串。
    【解决方案2】:

    您的代码一遍又一遍地将循环中的拆分分配给word 变量,每次都覆盖word。然后,您将 word 拆分为其字符并尝试对其进行洗牌。您应该改组拆分数组。

    使用 LINQ 的示例:

    public static string[] ScrambleSentence(string sentence)
    {
        var random = new Random();
        return sentence.Split(' ').OrderBy(x => random.Next()).ToArray();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多