練習題 (13):Implement word wrapping feature (Observe how word wrap works in windows 'notepad')
這一題是實作 Winodws 中筆記本的【自動換行 】功能,自動換行就是以某各長度為限,但是又不能把單自從中切斷為主。
程式碼:
-
using System;
-
using System.Text;
-
namespace Wrapping
-
{
-
internal class Program
-
{
-
private static void Main( string [ ] args)
-
{
-
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.";
-
StringBuilder sb = new StringBuilder ( "" );
-
int start = 0, indx = 0;
-
const int LENGTH = 40;
-
while (start <= s.Length )
-
{
-
if ( ( (start + LENGTH) <= s.Length ) && (s[start + LENGTH - 1 ] != ' ' ) )
-
{
-
string temp_s = s.Substring (start, LENGTH);
-
indx = temp_s.LastIndexOf ( " " );
-
string append = s.Substring (start, indx);
-
sb.Append (append);
-
sb.Append (Environment.NewLine );
-
start += append.Length + 1;
-
indx = 0;
-
}
-
else
-
{
-
if ( (start + LENGTH) <= s.Length )
-
{
-
sb.Append (s.Substring (start, LENGTH) );
-
}
-
else
-
{
-
sb.Append (s.Substring (start) );
-
}
-
sb.Append (Environment.NewLine );
-
start += LENGTH;
-
}
-
}
-
Console.Write (sb);
-
}
-
}
-
}
|