C# 練習題 (13)

C# 練習題 (13)

練習題 (13):Implement word wrapping feature (Observe how word wrap works in windows 'notepad')

這一題是實作 Winodws 中筆記本的【自動換行 】功能,自動換行就是以某各長度為限,但是又不能把單自從中切斷為主。

程式碼:

  1. using System;
  2. using System.Text;
  3. namespace Wrapping
  4. {
  5. internal class Program
  6. {
  7. private static void Main( string [ ] args)
  8. {
  9. String s = "Chien-Ming Wang tries to make it two straight wins for the Yankees. In his only start of this season -- because he's been held back by a hamstring injury -- Wang lost to the Devil Rays, giving up nine hits and four runs in 6 1/3 innings. \"Hopefully Wang can pick up where our pitching staff left off,\" Jeter said.";
  10. StringBuilder sb = new StringBuilder( "" );
  11. int start = 0, indx = 0;
  12. const int LENGTH = 40;
  13. while (start <= s.Length )
  14. {
  15. if ( ( (start + LENGTH) <= s.Length ) && (s[start + LENGTH - 1 ] != ' ' ) )
  16. {
  17. string temp_s = s.Substring (start, LENGTH);
  18. indx = temp_s.LastIndexOf ( " " );
  19. string append = s.Substring (start, indx);
  20. sb.Append (append);
  21. sb.Append (Environment.NewLine );
  22. start += append.Length + 1;
  23. indx = 0;
  24. }
  25. else
  26. {
  27. if ( (start + LENGTH) <= s.Length )
  28. {
  29. sb.Append (s.Substring (start, LENGTH) );
  30. }
  31. else
  32. {
  33. sb.Append (s.Substring (start) );
  34. }
  35. sb.Append (Environment.NewLine );
  36. start += LENGTH;
  37. }
  38. }
  39. Console.Write (sb);
  40. }
  41. }
  42. }