2015-09-19 45 views
0

我有一個大約4MB(400萬字符)的字符串和大約30.000行的變量。接下來我有一個字符的索引,可以說3605506,找到這個字符在哪一行上最快最有效的方法是什麼?我需要在彼此之後做數百次,所以這是相對重要的,因爲它是高效的。按行查找位置

+0

我把它的行長度是可變的嗎? – nnnnnn

+0

@nnnnnn是的,我現在已經實現了一個非常低效的臨時解決方案,我每次都在循環播放,並與角色位置進行比較......但它太慢而且感覺非常糟糕。 – user5354681

+0

這個問題聽起來類似於 - > [確定行號從文本文件中的字節偏移](http://stackoverflow.com/questions/13609535/determine-line-number-from-byte-offset-in-a-text -文件)。 \t 您需要掃描文件並計算在接近字節偏移量時發現的新行數。 –

回答

1

將字符串和和索引傳遞給下面的函數。它根據新的行字符拆分字符串,並檢查計數是否已通過索引值。

function getlineNumberofChar(data,index) { 
    var perLine = data.split('\n'); 
    var total_length = 0; 
    for (i = 0; i < perLine.length; i++) { 
     total_length += perLine[i].length; 
     if (total_length >= index) 
      return i + 1; 
    } 
} 
+0

不能贊成,但我真誠的驚喜你的代碼實際上是比我自己的簡單循環更高性能:http://jsperf.com/line-from-position – user5354681

+0

你可以檢查這個聲明是否返回答案? data.substring(0,index).split('\ n')。長度 –

+0

除了我沒有意識到你的函數返回了一行字節偏移量而不是行號,但這應該很容易修復(就像我在jsperf中所做的那樣) – user5354681

0
// Let this be your 4MB string. 
var str = "This \n is a\n test\n string." 

// Let this be the index of the character you are finding within the 4MB string. 
var index = str.indexOf("test") 

// Create substring from beginning to index of character. 
var substr = str.substring(0, index) 

// Count the number of new lines. 
var numberOfLines = (function(){ 
try{ 
    // Add 1 to final result to account for the first line. 
    return substr.match(new RegExp("\n", "g")).length + 1 
} catch(e){ 
    // Return 1 if none found because the character is found on the first line. 
    return 1 
}})()