用字分割一半的字符串 [英] Split String in Half By Word

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

问题描述

我处在一种情况下,我想取一个字符串并将其分成两半,尊重单词,以便此字符串不会分裂成此str 此处,而不是将其分成此字符串 此处

I'm in a situation where I'd like to take a string and split it in half, respecting words so that this string here doesn't get split into this str ing here, rather it would be split into this string here.

我认为一个开始步骤是将字符串拆分为基于空格的数组,然后根据这些部分计算长度,但在我的尝试中,更长的字符串结束被错误分割。

I figure a starting step would to be to split the string into an array based on spaces, then calculate length based on those pieces, but in my attempts longer strings end up being split up incorrectly.

推荐答案

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

Look for the first space before and after the middle, and pick the one closest to the middle.

示例:

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/

(此代码假设中间两侧实际上有空格。你会还要在之前添加对的检查,在之后添加 -1 的检查。 )

(This code assumes that there actually are spaces on both sides of the middle. You would also add checks for before and after being -1.)

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

The check that I talked about in the node would be done correctly like this:

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

这是一个小提琴,您可以在其中编辑文本并立即查看结果: http://jsfiddle.net/Guffa/7RNBu/11/

Here is a fiddle where you can edit the text and see the result immediately: http://jsfiddle.net/Guffa/7RNBu/11/

这篇关于用字分割一半的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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