将字符串分割成更小的字符串按长度可变 [英] Split String into smaller Strings by length variable

查看:202
本文介绍了将字符串分割成更小的字符串按长度可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想掰开一个字符串按一定的长度是可变的。照片 它需要边界检查时字符串的最后一节是不是只要或大于长度,以免发生爆炸。寻找最简洁的(但可以理解的)版本。

例如:

 字符串x =AAABBBCC;
字符串[] ARR = x.SplitByLength(3);
//改编[0]  - > AAA;
//改编[1]  - > BBB;
// ARR [2]  - > CC的
 

解决方案

您需要使用一个循环:

 公共静态的IEnumerable<字符串> SplitByLength(此字符串str,INT最大长度){
    对于(INT指数= 0;指数< str.Length;指数+ =最大长度){
        (,Math.Min(最大长度,str.Length指数 - 指数))收益率的回报str.Substring;
    }
}
 

另一种方法:

 公共静态的IEnumerable<字符串> SplitByLength(此字符串str,INT最大长度){
    INT索引= 0;
    而(真){
        如果(指数+最大长度> = str.Length){
            收益回报str.Substring(指数);
            产生中断;
        }
        收益回报str.Substring(指数,最大长度);
        指数+ =最大长度;
    }
}
 

2 第二替代:(对于那些谁也受不了,而(真)

 公共静态的IEnumerable<字符串> SplitByLength(此字符串str,INT最大长度){
    INT索引= 0;
    而(指数+最大长度< str.Length){
        收益回报str.Substring(指数,最大长度);
        指数+ =最大长度;
    }

    收益回报str.Substring(指数);
}
 

I'd like to break apart a String by a certain length variable.
It needs to bounds check so as not explode when the last section of string is not as long as or longer than the length. Looking for the most succinct (yet understandable) version.

Example:

string x = "AAABBBCC";
string[] arr = x.SplitByLength(3);
// arr[0] -> "AAA";
// arr[1] -> "BBB";
// arr[2] -> "CC"

解决方案

You need to use a loop:

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
    for (int index = 0; index < str.Length; index += maxLength) {
        yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
    }
}

Alternative:

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
    int index = 0;
    while(true) {
        if (index + maxLength >= str.Length) {
            yield return str.Substring(index);
            yield break;
        }
        yield return str.Substring(index, maxLength);
        index += maxLength;
    }
}

2nd alternative: (For those who can't stand while(true))

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
    int index = 0;
    while(index + maxLength < str.Length) {
        yield return str.Substring(index, maxLength);
        index += maxLength;
    }

    yield return str.Substring(index);
}

这篇关于将字符串分割成更小的字符串按长度可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆