用字分割一半的字符串

编程入门 行业动态 更新时间:2024-10-25 00:32:29
本文介绍了用字分割一半的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我处在一种情况下,我想取一个字符串并将其分成两半,尊重单词,以便此字符串不会分裂成此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);

演示: jsfiddle/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; }

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

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

更多推荐

用字分割一半的字符串

本文发布于:2023-11-29 00:29:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用字   字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!