我正在尝试用空格分隔字符串中的单词。
例如,我想将"twothousandninehundredfiftyeight"
转换为"two thousand nine hundred fifty eight"
(以便以后再将其转换为2958,但我已经知道了)
我设法使用数组字典使其工作:
var dictionary = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","fourty","forty","fifty","sixty","seventy","eighty","ninety","hundred","thousand"];
具有以下两个功能:
function spaceinsert(x) {
for (i = 0; i < dictionary.length; i++) {
if (x.includes(dictionary[i])) {
var pos = getIndicesOf(dictionary[i],x);
for (g = 0; g < pos.length; g++) {
if (pos[g] != -1 && pos[g] !=0) {
x = [x.slice(0,pos[g])," ",x.slice(pos[g])].join('');
}
}
}
}
return x
}
和
function getIndicesOf(searchStr,str,caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0,index,indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr,startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
(抱歉,代码混乱,这是我的新手)
此功能适用于大多数数字。例如:
onethousandthreehundredsixtyfive
转换为one thousand three hundred sixty five
,但无法处理其他数字,例如seventhousandtwohundredtwentytwo
它将转换为seven thousand two hundredtwent ytwo
。 sixthousandfourhundredeightyeight
转换为six thousand four hundred eight yeight
,我认为这与重复出现的“单词”有关( TWO hundredtwenty TWO ),但我不知道找出解决这个问题的方法。
有什么想法吗?