2009-07-01 82 views
0

我有一个字典对象IDictionary<string, string>,它只包含以下项目: Item1,Items2和Item3。每个项目的最大长度为50个字符。如何将长字符串拆分为固定数组项目

然后我有一个单词列表List<string>。我需要一个循环来遍历单词并将它们添加到从Item1开始的字典中,但在将其添加到字典之前,需要检查长度。如果新项目和当前项目的长度加在一起大于50个字符,则该单词需要向下移动到下一行(在本例中为Item2)。

这样做的最好方法是什么?

+0

所以你想让我们写你的算法和代码? – 2009-07-01 14:49:26

回答

6

我不知道为什么这个问题得到了非常多的投票,但也许原因是你有一个非常明确的算法,所以它应该是微不足道的C#代码。就目前而言,要么你没有经验,要么真的很懒惰。我将假设前者。

不管怎么说,让我们一起来看看需求。

1)“然后我有一个单词列表。”你已经有了某种形式的这条线。

List<string> words = GetListOfWords(); 

2)“经过的话,将它们添加到开始项目1字典” - 我推荐一个列表,而不是一本字典的,如果你要的字符串的序列。另外,您需要一个临时变量来存储当前行的内容,因为您一次只添加一行完整行。

var lines = new List<string>(); 
string currentLine = ""; 

3)“我需要一个循环,将通过话”

foreach(var word in words) { 

4)“如果新的项目,加在一起当前项目的长度大于50个字符” - +1的空间。

if (currentLine.Length + word.Length + 1 > 50) { 

5)“那么这个词需要向下移动到下一行”

 lines.Add(currentLine); 
     currentLine = word;  
    } 

6)“经过的话,将它们添加到开始项目1字典” - 你没这句话很清楚。你的意思是你想把每个单词加入最后一行,除非它使行数超过50个字符。

else { 
     currentLine += " " + word; 
    } 
} 
lines.Add(currentLine); // the last unfinished line 

你去了。


如果你绝对需要它作为有3条线路一个IDictionary,只是做

var dict = new Dictionary<string,string>(); 
for(int lineNum = 0; lineNum < 3; lineNum ++) 
    dict["Address"+lineNum] = lineNume < lines.Length ? lines[lineNum] : ""; 
0

我现在有这个,想知道是否有可能是一个更好的解决方案:


public IDictionary AddWordsToDictionary(IList words) 
{ 
    IDictionary addressParts = new Dictionary(); 
    addressParts.Add("Address1", string.Empty); 
    addressParts.Add("Address2", string.Empty); 
    addressParts.Add("Address3", string.Empty); 

    int currentIndex = 1; 
    foreach (string word in words) 
    { 
     if (!string.IsNullOrEmpty(word)) 
     { 
      string key = string.Concat("Address", currentIndex); 
      int space = 0; 
      string spaceChar = string.Empty; 
      if (!string.IsNullOrEmpty(addressParts[key])) 
      { 
       space = 1; 
       spaceChar = " "; 
      } 
      if (word.Length + space + addressParts[key].Length > MaxAddressLineLength) 
      { 
       currentIndex++; 
       key = string.Concat("Address", currentIndex); 
       space = 0; 
       spaceChar = string.Empty; 
       if (currentIndex > addressParts.Count) 
       { 
        break; // To big for all 3 elements so discard 
       } 
      } 

      addressParts[key] = string.Concat(addressParts[key], spaceChar, word); 
     } 
    } 

    return addressParts; 
} 
0

我只会做以下事情,并做你喜欢的结果“线”

static List<string> BuildLines(List<string> words, int lineLen) 
    { 
     List<string> lines = new List<string>(); 
     string line = string.Empty; 
     foreach (string word in words) 
     { 
      if (string.IsNullOrEmpty(word)) continue; 

      if (line.Length + word.Length + 1 <= lineLen) 
      { 
       line += " " + word; 
      } 
      else 
      { 
       lines.Add(line); 
       line = word; 
      } 
     } 
     lines.Add(line); 
     return lines; 
    }