2014-12-16 9 views
0

그래서 저는 strtok을 자바 스크립트로 구현했습니다. 어떤 이유로 문자열에 여러 개의 구분 기호를 연속적으로 전달하려고하면 다른 모든 구분 기호를 문자로 구문 분석합니다. 예를 들어, "This,, and that"","" "으로, [This, ,, and, that]의 배열을 반환합니다. 두 번째 쉼표는 다른 구분 기호 다음에 오는 문자이므로 구분 기호가 아닌 문자로 간주됩니다.String tokenizer가 null 토큰 또는 행의 여러 구분 기호를 올바르게 처리하지 않습니다.

여기에 코드입니다 :

//@param str: a string to tokenize 
//@param tok: an array of chars to be delimiters 
//@return: an array of strings. 

var strtok = function(str, tok) 
{ 
    if(str === "") return []; 

    var ret = [], 
    _buffer = str, 
    sub, 
    b = _buffer.charAt(0), 
    start = 0, 
    i = 0, 
    len = _buffer.length; 

    while(i <= len) { 
     b = _buffer.charAt(i); 
     tok.forEach(function(elm) { 
      if (b === elm) {    
       sub = _buffer.slice(start, i); 
       if(!(sub in tok)) ret.push(sub); 
       start = ++i; 
       return; 
      } 
     }); 
     i++; 
    } 
    ret.push(_buffer.slice(start, len)); 
    return ret; 
} 

var str = "This,, that"; 
var tok = '. ,'.split(''); 
console.log(strtok(str,tok)); 
// ["This", ",", "that"] 
str = "This,,, that"; 
console.log(strtok(str, tok)); 
// ["This", ",", " that"] <- notice the space before that 

답변

1

지수가 overincremented 비난 라인 start = i + 1; 것 수정 start = ++i;입니다됩니다.