我最近開始學習c#,但遇到了問題。這個問題給了我一個句子和一個數字,我的程式必須回傳那個數字的單詞。這是我所做的:
using System;
string inputData = Console.ReadLine();
string text = inputData;
inputData=Console.ReadLine();
int x = Convert.ToInt32(inputData);
string currentWord = String.Empty;
int wordCount = 1;
for (int i = 0; i < text.Length; i)
{
if (text[i] == ' ')
{
wordCount ; currentWord = String.Empty;
while (text[i] == ' ') i ;
}
if (text[i] != ' ') { currentWord = text[i]; }
if (wordCount == x) Console.WriteLine(currentWord);
}
Console.Read();
對于句子“我有兩支筆”和數字 2,程式回傳 h ha hav have。我做錯了什么?
uj5u.com熱心網友回復:
我會稍微改變一下。它給出多個值的問題是因為您沒有終止迭代。(打破forloop)。我已經添加了一些評論:
class Program
{
static void Main(string[] args)
{
// some test data (instead of readline)
string inputData = " I have two pens";
string text = inputData;
inputData = "2";
int x = Convert.ToInt32(inputData);
string currentWord = String.Empty;
int wordCount = 1;
for (int i = 0; i < text.Length; i )
{
// when the character is a space and the currentWord has something or it was the last character of the text
// a new word has been found.
if ((text[i] == ' ' && !string.IsNullOrEmpty(currentWord)) || i==text.Length-1))
{
// when a new word has been found, just check it.
if (wordCount == x)
{
Console.WriteLine(currentWord);
// this is where your solution fails.
// when the word has been found, break the iteration.
break;
}
wordCount ;
currentWord = String.Empty;
}
else if (text[i] != ' ')
{
currentWord = text[i];
}
}
Console.Read();
}
}
您可以為此使用 System.Linq,這要容易得多。
// Split the string on space and create an array.
// Skip some elements and select the first.
var s = text.Split(' ').Skip(x).FirstOrDefault();
Console.WriteLine(s);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/486710.html
上一篇:試圖了解流量控制/圖表
