c# - 在可变数量的字符之后分割字符串

标签 c# .net

我想在可变数量的字符之后拆分名为: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;
    }
}

编辑: 上面给出的解决方案并不完全适合我,也许当我发布练习时它会有所帮助:

|| crypt n m d text || text is padded with spaces until its length is a multiple of n || the characters in text are circulary shifted in the alphabet by the displacement d || example: if d = 1 then 'a' -> 'b' , 'b' -> 'c' .... etc... 'z' -> 'a' || text is divided in blocks of length n characters || inside every block of n the characters are circulary shifted m times to the left || the shifted groups are concatenated

我已经解决了m和d,只需解决n即可。


上面给出的解决方案并不完全适合我,也许当我发布练习时它会有所帮助:

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

我已经解决了m和d,只需解决n即可。

最佳答案

这是您想要的代码,无需通过字符数组:

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

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

你可以这样调用它:

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

你可以找到一个例子LINQPad程序here .

关于c# - 在可变数量的字符之后分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16963484/

相关文章:

c# - 使用 Regex 前瞻将信用卡号分成 4 个 block ?

c# - 如何在不在服务器上安装 SSIS 的情况下在 C# 应用程序中使用 SSIS 包,这可能吗?

c# - 'System.ServiceModel.Diagnostics.TraceUtility' 的类型初始值设定项抛出异常

c# - Entity Framework 返回数据库中不存在的实体

c# - 我如何获得 System.Windows.Window

c# - 来自 BlobItem 的 URL

c# - ASP.NET MVC 5 中的 DateCreated 和 DateModified

java - 可以使用类接口(interface)代替 AOP 来实现关注点分离吗?

.net - 通过 LINQ 查询突破 Parallel.ForEach

c# - C#中的线程问题