2014-10-01 66 views
0

我有一个文本文件,我想添加一个文本块来使用Go。该文本文件看起来像这样(没有编号)将字符串添加到Go中的现有文本文件中

  1. 等等
  2. blah2
  3. ]
  4. blah3
  5. blah4

,我希望它看起来像这样

  1. blah
  2. blah2
  3. 我插入的文本这里
  4. ]
  5. blah3
  6. blah4

假设我已经打开的文件和创建的每个行的所谓'文件中的字符串数组线。

//find line with ] 
for i, line := range lines { 
    if(strings.ContainsRune(line, ']')) { 
     //take the line before ']'... and write to it somehow 
     lines[i-1] (?) 

    } 
} 

我该怎么做?

回答

0
lines = append(lines[:i], 
      append([]string{"MY INSERTED TEXT HERE"}, lines[i:]...)...) 

lines = append(lines, "") 
copy(lines[i+1:], lines[i:]) 
lines[i] = "MY INSERTED TEXT HERE" 

第二种方法是更有效的。这两种方法列在有用的SliceTricks页面上。

0

如果你想用切片做到这一点,你可以插入你想要的字符串在正确的索引。

// make the slice longer 
lines = append(lines, "") 
// shift each element back 
copy(lines[i+1:], lines[i:]) 
// now you can insert the new line at i 
lines[i] = x 
相关问题