Image Here我正在尝试执行此程序,当我在输入字段中输入一个字母时,输出文本显示输入文本字母后面的字母,如a应为b,或b应为c,等等。所以我想我可以为字母表创建一个字符串数组,如果输入字母等于循环数组的索引,那么结果将等于索引+ 1.我尝试了它,它只是给了我相同的作为输入的东西。我错过了什么吗?
export {}
declare global {
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason: Error) => void) => void): Promise<T>;
}
}
答案 0 :(得分:1)
我建议使用 Dictionary ,而不是数组。首先创建它:
using System.Linq;
...
// {{'a', 'b'},
// {'b', 'c'},
// ...
// {'y', 'z'},
// {'z', 'a'}}
const int range = 'z' - 'a' + 1;
static Dictionary<char, char> s_Dict = Enumerable
.Range('a', range) // all letters enumerated
.Select(item => new {
key = (char) item,
value = (char) ('a' + (item - 'a' + 1) % range),
})
.ToDictionary(item => item.key,
item => item.value);
然后使用它
public static string Encrypt(string source) {
if (null == source)
return null; // or throw ArgumentNullException
// out var - C# 7.0 syntax
return string.Concat(source
.Select(c => s_Dict.TryGetValue(c, out var cNew) // do we have a key?
? cNew // if true, put the corresponding value
: c)); // if false, leave the character intact
}
测试:
string test = "encrypt me, please!";
Console.WriteLine(test);
Console.WriteLine(Encrypt(test));
结果:
encrypt me, please!
fodszqu nf, qmfbtf!
答案 1 :(得分:0)
一个天真的实现,不使用Linq立即在团结中玩弄
using System.Collections.Generic;
using UnityEngine;
public class Encryption : MonoBehaviour {
public string testString = "Every lower case vowel gets replaced by the 'next' one.";
Dictionary<char, char> charMap;
string result = "";
void Start () {
charMap = new Dictionary<char, char>() {
{'a','e'},
{'e','i'},
{'i','o'},
{'o','u'},
{'u','a'}
};
result = "";
for (int i = 0; i < testString.Length; i++) {
result += charMap.ContainsKey(testString[i]) ? charMap[testString[i]] : testString[i];
}
Debug.Log(result);
}
}