分割関数を作成しました。文中のすべての単語がstring
配列の要素として追加されます。
最後の言葉に問題があります。出力配列に追加されていません:
コード:
// the funcion
static void splits(string str)
{
int i=0;
int count=0;
string[] sent = new string[2];
string buff= "";
while (i < str.Length)
{
if (str[i] == ' ')
{
sent[count] = buff;
count++;
buff = "";
}
buff += str[i];
i++;
}
Console.WriteLine(sent[0]);
}
// When used
splits("Hello world!");
-----------------------------------------------
私は解決策を見つけました、そしてそれは非常に簡単
です私は皆が恩恵を受けることを願っています
static void splits(string str)
{
int i = 0;
int count = 0;
string[] sent = new string[2];
string buff = "";
str += " "; // the solution here, add space after last word
while (i < str.Length)
{
if (str[i] == ' ')
{
sent[count] = buff;
count++;
buff = "";
}
buff += str[i];
i++;
}
for (int z = 0; z < sent.Length; z++)
{
Console.WriteLine(sent[z].Trim());
}
}
結果は次のようになります(ここでは視覚的な結果)
Hello
world!