按单词将字符串一分为二

Split String in Half By Word

本文关键字:一分为二 字符串 单词      更新时间:2023-09-26

我现在的情况是,我想把一个字符串一分为二,尊重单词,这样this string here就不会被拆分为this str ing here,而是会被拆分为this string here

我想一个开始的步骤是将字符串分割成一个基于空格的数组,然后根据这些片段计算长度,但在我的尝试中,较长的字符串最终被错误地分割。

查找中间前后的第一个空格,然后选择最靠近中间的一个。

示例:

var s = "This is a long string";
var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);
if (middle - before < after - middle) {
    middle = before;
} else {
    middle = after;
}
var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);

演示:http://jsfiddle.net/7RNBu/

(此代码假设中间两侧实际上都有空格。您还需要添加beforeafter-1的检查。)

编辑:

我在节点中谈到的检查将正确完成,如下所示:

if (before == -1 || (after != -1 && middle - before >= after - middle)) {
    middle = after;
} else {
    middle = before;
}

这里有一个小提琴,你可以编辑文本并立即看到结果:http://jsfiddle.net/Guffa/7RNBu/11/

我想把它作为注释,但没有足够的代表点。顶级解决方案现在很容易失败,因为它在使用indexOf方法时不检查"-1"。看看这个小提琴:

http://jsfiddle.net/7RNBu/7/

var s = "This is a long strinjjjjjjjjjjjjjjjjg";
var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);
if (middle - before < after - middle) {
    middle = before;
} else {
    middle = after;
}
var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);

您可能还关心换行符、制表符和空格,所以我会使用这样的正则表达式:

var s = "this string here";
var idx = s.length / 2;

while (idx < s.length && s[idx].match(/'s/) == null)
    idx++;
var s1 = s.substring(0, idx);
var s2 = s.substring(idx);
document.getElementById("s1").innerText = s1;
document.getElementById("s2").innerText = s2;

看看这把小提琴:http://jsfiddle.net/nS6Bj/5/

let str = 'qwerty';
let half = Math.floor(str.length / 2);
str = str.slice(0, half) + ' ' + str.slice(half, str.length);
//output
'qwe rty'

我最初以为我有一个错误,但我最终解决了它。

现在来分解使用的逻辑:

var calculate = function(initialString) {
  var halfwayPoint = Math.floor(initialString.length / 2);
  var strArray = initialString.split(' ');
  // Caluclate halfway point, then break string into words
  var wordFlag;  // Will be split point
  var charCount = 0;
  _.each( strArray, function(word, strArrayIndex) {
    if (wordFlag) return false;
    // If we have the location, exit
    // If charCount is before the halfway point
    // and the end of word is after halfway point
    // Then set the flag
    // We add strArrayIndex to the word length to include spaces
    if (charCount <= halfwayPoint && 
      ((charCount + word.length + strArrayIndex) >= halfwayPoint) ) {
      wordFlag = strArrayIndex;
      return false;
    }
    // Increase charCount to be length at the end of this word
    charCount += (word.length);
  });
  if (!wordFlag) return null;
  // Split the word array by the flag we figured out earlier
  var lineOneArray = strArray.slice(0, (wordFlag + 1));
  var lineTwoArray = strArray.slice(wordFlag + 1);

  // We now join the word arrays into a string, stripping beginning and ending spaces.
  var stOne = (lineOneArray.join(' ')).replace(/^'s's*/, '').replace(/'s's*$/, '');
  var stTwo = (lineTwoArray.join(' ')).replace(/^'s's*/, '').replace(/'s's*$/, '');
  // Finally return the split strings as an array.
  return [stOne, stTwo];
};

如果有人看到我的逻辑有漏洞,请告诉我!不过,我确信这在大多数情况下都有效。

如果你希望第二个字符串比第一个长(即在中间单词之前而不是之后有换行符),那么不要在wordFlag中加+1。

这将根据字数(而不是字符数,因此根据长短词的位置,每一半的确切长度可能会有很大不同)来分割字符串。

var s = "This is a string of filler text";
var pieces = s.split(" "),
    firstHalfLength = Math.round(pieces.length/2),
    str1 = "",
    str2 = "";
for (var i = 0; i < firstHalfLength; i++){
    str1 += (i!=0?" ":"") + pieces[i];
}
for (var i = firstHalfLength; i < pieces.length; i++){
    str2 += (i!=firstHalfLength?" ":"") + pieces[i];
}
document.write(s);
document.write("<br />"+str1);
document.write("<br />"+str2);
// Output
This is a string of filler text
This is a string
of filler text

http://jsfiddle.net/daCrosby/7RNBu/2/

         <h1>
              <span>
                // for first half start from 0 till middle
                {title.substring(0, title.length / 2)}
              </span>
              <span>
                // second half just point the starting point
                {title.substring(title.length / 2)}
              </span>
         </h1>