将字符串拆分为定义长度的部分

时间:2015-07-16 11:11:58

标签: javascript arrays string split

我想将一个字符串拆分成具有定义长度的部分。这意味着如果我有一个像"1234567890"这样的给定字符串,并希望将其拆分为长度为3的部分,那么我希望结果为["123", "456", "789", "0"]。为了实现这个目标,我在这里找到了一个解决方案:https://stackoverflow.com/a/14349616/2577116

现在,我还想分开,不是从开头开始,而是在字符串的末尾。预期结果为["1", "234", "567", "890"]

因此,我使用并修改了上面的解决方案并提出了这个:

function (str, len, reversed) {
        //create array from string
    var _parts = str.split(""),
        _size = Math.ceil(_parts.length/len),
        _ret  = [],
        _offset;

    //should give ["123", "456", "789", "0"]
    if (!reversed) {
        for (var _i=0; _i<_size; _i++) {
            _offset = _i * len;
            _ret[_i] = _parts.slice(_offset, _offset+len).join("");
        }
    }
    //should give ["1", "234", "567", "890"]
    else {
        //reverse input
        _parts.reverse();
        //apply same algorithm as above but don't join yet
        for (var _j=0; _j<_size; _j++) {
            _offset = _j * len;
            _ret[_j] = _parts.slice(_offset, _offset+len);
        }
        //bring each subitem back to right order, join
        _ret.forEach(function (item, i) {
            _ret[i] = item.reverse().join("");
        });
        //reorder items
        _ret.reverse();
    }

    return _ret;
}

这看起来效果很好。 我要求一些更好/简化的解决方案,因为我感觉有点笨重。

6 个答案:

答案 0 :(得分:2)

我会做这样的事情:

    function foo(str,len,rev) {
      var result = [];
      if (rev && str.length%len != 0) {
        result.push(str.substr(0, str.length % len));
        str=str.substr(str.length % len);
      }

      for (var i=0; i<str.length; i+=len) {
        result.push(str.substr(i,len));
      }
      return result;
    }

if语句将首先检查reverse是否为true,如果是,它将在将字符串的长度除以块大小时计算余数(检查modulo operation %)。然后使用函数&#34; substr&#34;,它获取起始位置和长度,以获得列表的第一个元素。

for循环将遍历字符串&#34; len&#34;当时的字符再次使用函数&#34; substr&#34;把绳子切成长片&#34; len&#34;并将它们添加到列表结果中。

答案 1 :(得分:1)

您可以通过重新排列字符串并使用您指向的相同chunkString函数来完成此操作。

> chunkString(s.split('').reverse().join(''), 3).map(function(v){return v.split('').reverse().join('');}).reverse()
< ["1", "234", "567", "890"]

split, reverse, join用于将字符串转换为列表,反向,然后转换回字符串 可重复的代码 -

chunkString(
    s.split('').reverse().join(''),
    3
).map(
    function(v){
        return v.split('').reverse().join('');
    }
).reverse()

答案 2 :(得分:1)

如果您更喜欢RegEx:

"1234567890".match(/(.{1,3})|(.{1,})/g)

输出:

["123", "456", "789", "0"]

反向

var splitLength = 3
var _str = "1234567890"
var startSubStringLength = _str.length % splitLength

_str.match(new RegExp("(^.{1," + startSubStringLength + "})|(.{1,3})|(.{1,})", "g"))

输出:

["1", "234", "567", "890"]

完整功能

var _mySplit = function(str, splitLength, doReverse) {
    var _regEx = new RegExp("(.{" + splitLength + "})|(.{1,})", "g");
    if(doReverse) {
        var startSubStringLength = str.length % splitLength
        if(startSubStringLength > 0) {
            _regEx = new RegExp("(^.{1," + startSubStringLength + "})|(.{1," + splitLength +  "})|(.{1,})", "g")
        }
    }
    return str.match(_regEx)
}

输出:

_mySplit("1234", 3, false)
["123", "4"]
_mySplit("1234", 3, true)
["1", "234"]
_mySplit("1234567890", 3, true)
["1", "234", "567", "890"]
_mySplit("1234567890", 3, false)
["123", "456", "789", "0"]

答案 3 :(得分:1)

试试这个:

步骤:

  1. 反转字符串
  2. 将其拆分为三个字符的组合
  3. 反转字符串
  4. 代码:

    void theBoxCell_DrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index < 0) return;
        string t = theBoxCell.Items[e.Index].ToString();
        using (SolidBrush brush = new SolidBrush(
            (e.State & DrawItemState.Selected) != DrawItemState.None ?
                       Color.LightCyan : Color.LightGray))
            e.Graphics.FillRectangle(brush, e.Bounds);
        e.DrawFocusRectangle();
        e.Graphics.DrawString(t, Font, Brushes.DarkGoldenrod, e.Bounds.X + 6, e.Bounds.Y + 1);
    
    }
    

    更短 Less Redable

    var str = '1234567890';
    var rev = str.split('').reverse().join('');
    
    var matches = rev.match(/([0-9]{1,3})/g).reverse().map(function(el) {
      return el.split('').reverse().join('');
    });
    console.log(matches);

答案 4 :(得分:0)

我的解决方案:

function mySplit (str, len, reversed) {
        //create array from string
  var _parts = str.split(""),
      _size = Math.ceil(_parts.length/len),
      _ret  = [],
      _offset;


  for (var _i=0; _i<_size; _i++) {
    _offset = Math.abs((reversed ? _parts.length : 0 ) - (_i * len));
    var sliceStart = reversed ? Math.max(0, _offset - len) : _offset;
    var sliceEnd = reversed ? _offset : _offset + len;
    _ret.push(_parts.slice(sliceStart, sliceEnd).join(""));
  }
  reversed && _ret.reverse();


  return _ret;
}

var log = document.getElementById('log');

log.innerHTML += "string : 1234567890";
log.innerHTML += "\nreversed:" + mySplit("1234567890", 3, true)
log.innerHTML += "\nnot reversed:" + mySplit("1234567890", 3, false)

log.innerHTML += "\n\nstring : 123456789";
log.innerHTML += "\nreversed:" + mySplit("123456789", 3, true)
log.innerHTML += "\nnot reversed:" + mySplit("123456789", 3, false)
<pre id="log"></pre>

答案 5 :(得分:0)

这就是我所做的。

var string = '1234567890';
var chunks = 3;

console.log( sliceIt(string, chunks, true) );
console.log( sliceIt(string, chunks, false) );



function sliceIt( str , steps , rev ) {

  var iterations  = Math.ceil(str.length); // for the loop
  var returnArray = [];
  var strLen      = str.length;
  var modulo      = strLen % steps; // for reverse purposes

  // if modulo is 0 then no action needed. returns the modulo if both true
  var firstStep       = (rev === true) && (modulo != 0) ? modulo : false;  

  for (i=0; i < iterations;) {        

      // pushing to array
      returnArray.push(str.substr( i , firstStep || steps ));   

      // increment the right way 
      i+= firstStep || steps; 

      // first step done.. deactivate
      firstStep = false; 
    }
    return returnArray;
  }