Split string to two, will have almost same length

前端 未结 3 1303
迷失自我
迷失自我 2021-01-28 20:58

I have string: \"This is a sample string\", and I need to split it to 2 strings, without break the words, and that the two strings will have the closest length, so the result wi

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-28 21:27

    you can split your words by space

    e.g.:

    var words = 'George is nice'
    words = words.split(' ')
    

    and then walk through the array and compare string lengths. As example

    var concat = ''
    for (var word in words)
    {
        word = words[word]
        if (word.length < words[word - 1] )
        {
            concat += word
        }
    }
    

    it would be nice to know why it has to be only 2 elements, not the amount of words? Are you going for some algorithm? or do you just want to group the least amount of text needed together?

    It would be nice to see why you need this.

提交回复
热议问题