将字符串拆分为两个,长度几乎相同

Split string to two, will have almost same length

我有字符串:"This is a sample string",我需要将它拆分为 2 个字符串,不打断单词,并且两个字符串的长度最接近,所以结果将是:

["This is a", "sample string"].

另一个e.x.:

"Gorge is nice" => ["Gorge", "is nice"]

另外,如果函数可以获取我将作为结果获取的元素数量作为参数,那就太好了。

感谢您的帮助!

你可以按 space

拆分你的单词

例如:

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

然后遍历数组并比较字符串长度。 例如

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

很高兴知道为什么它必须只有 2 个元素,而不是单词的数量? 你要一些算法吗?还是只想将所需的最少文本组合在一起?

很高兴知道您为什么需要这个。

可以使用indexOf,第二个参数作为字符串长度的一半。这样,indexOf 将在提供的索引之后搜索匹配字符串的下一个 索引

Demo

var str = "Thisasdfasdfasdfasdfasdf is a sample string",
  len = str.length;

var ind = str.indexOf(' ', Math.floor(str.length / 2) - 1);
ind = ind > 0 ? ind : str.lastIndexOf(' ');

var str1 = str.substr(0, ind),
  str2 = str.substr(ind);

document.write(str1 + ' <br /> ' + str2);


更新

what if i will need to split it to 3 or 4 or whatever elements?

function split(str, noOfWords) {
  // Set no. of words to 2 by default when nothing is passed
  noOfWords = noOfWords || 2;

  var len = str.length; // String length
  wordLen = Math.floor(len / noOfWords); // Approx. no. of letters in each worrd

  var words = [],
    temp = '',
    counter = 0;

  // Split the string by space and iterate over it
  str.split(' ').forEach(function(v) {
    // Recalculate the new word length
    wordLen = Math.floor((len - words.join(' ').length) / (noOfWords - counter));

    // Check if word length exceeds
    if ((temp + v).length < wordLen) {
      temp += ' ' + v;
    } else {
      // Add words in the array
      words.push(temp.trim());

      // Increment counter, used for word length calculation
      counter++;
      temp = v;
    }
  });

  // For the last element
  temp.trim() && words.push(temp.trim());
  return words;
}

var str = "This is a sample string. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos quae error ab praesentium, fugit expedita neque ex odio veritatis excepturi, iusto, cupiditate recusandae harum dicta dolore deleniti provident corporis adipisci.";

var words = split(str, 10);

console.log(words);
document.write('<pre>' + JSON.stringify(words, 0, 2) + '</pre>');

你可以试试像

这样的拆分器

function split(str) {
  var len = str.length,
    mid = Math.floor(len / 2);

  var left = mid - str.substring(0, mid).lastIndexOf(' '),
    right = str.indexOf(' ', mid) - mid;

  var ind = mid + (left < right ? -left : right);

  return [str.substr(0, ind),
    str2 = str.substr(ind)
  ];
}

var parts = split("123-456 3-5-asldfkjas kdfasdfasd fjas");
snippet.log(parts[0]);
snippet.log(parts[1]);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>