2

我想在可变数量的字符之后拆分我的字符串:invoerstring(n是字符串需要拆分时的字符数)。如果字符串长度比变量n短,则需要添加空格,直到字符串长度 = n。结果需要显示在名为 uitvoer 的文本字段中。

到目前为止是这样的:

string invoerstring = invoer.Text;

if (invoerstring.Length < n)
{
    invoerstring += "";
    char[] myStrChars = invoerstring.ToCharArray();
}

if (invoerstring.Length == n)
{
    string [] blok = invoerstring.Split();
    foreach (string word in blok)
    {
        uitvoer.Text = word;
    }
}

编辑:上面给出的解决方案并没有完全为我完成这项工作,也许在我发布练习时会有所帮助:

|| 加密 nmd 文本 || 文本用空格填充,直到它的长度是 n 的倍数 || 文本中的字符在字母表中循环移位 d || 例如:如果 d = 1 那么 'a' -> 'b' , 'b' -> 'c' .... 等等... 'z' -> 'a' || 文本被分成长度为 n 个字符的块 || 在 n 的每个块内,字符循环向左移动 m 次 || 移位的组被连接起来

我已经解决了m,d只需要解决n。


上面给出的解决方案并没有完全为我完成这项工作,也许在我发布练习时会有所帮助:

|| 加密 nmd 文本 || 文本用空格填充,直到它的长度是 n 的倍数 || 文本中的字符在字母表中循环移位 d || 例如:如果 d = 1 那么 'a' -> 'b' , 'b' -> 'c' .... 等等... 'z' -> 'a' || 文本被分成长度为 n 个字符的块 || 在 n 的每个块内,字符循环向左移动 m 次 || 移位的组被连接起来

我已经解决了m,d只需要解决n。

4

3 回答 3

4

Here's the code you want, no need to go through a character array:

public static string EnsureExactLength(this string s, int length)
{
    if (s == null)
        throw new ArgumentNullException("null");

    return s.PadRight(length).Substring(0, length);
}

You call it like this:

string s = "Test string".EnsureExactLength(4); // will return "Test"
string s = "Te".EnsureExactLength(4);          // will return "Te  "

You can find an example LINQPad program here.

于 2013-06-06T13:36:50.130 回答
1

Okay, I'm honestly not sure what the code you have above is doing because I see calls like Split() without any parameters, and stuff. But to meet the requirements, this one line should do:

string invoerstring = invoer.Text.PadRight(n, ' ').Substring(0, n);

the PadRight will make sure it's as long as n and the Substring will then return the portion of the string up to n.

If you then wanted that string in an array, because I see you have one at the end, you could do this:

invoerstring.ToArray();
于 2013-06-06T13:36:30.083 回答
0

这是一个 LinqPad 脚本:

void Main()
{
    const string TEXT = "12345ABCDE12345ABCDE1234";
    const int LENGTH = 5;
    const char PAD = '#';

    Enumerable.Range(0, TEXT.Length / LENGTH)
        .Union(TEXT.Length < LENGTH ? new int[] { 1 } : new int[] {})
        .Select((index, item) => TEXT.Length < LENGTH 
                                    ? TEXT.PadRight(LENGTH, PAD)
                                    : TEXT.Substring(index * LENGTH, LENGTH))
        .Concat(TEXT.Length % LENGTH != 0 
                    ? new string[] { TEXT.Substring(TEXT.Length - (TEXT.Length % LENGTH)).PadRight(LENGTH, PAD) }
                    : new string[] { })                                 
        .Dump();

}
于 2013-06-06T14:15:11.040 回答