계산이 포함 된 문자열이 있습니다. 각 항목은 다음 항목 사이에 공백이 있습니다. 최근 20 개의 항목 만 보관하려면 어떻게합니까?문자열의 처음 20 개 항목 만 유지하십시오.
Label2.text += TextBox1.Text + "+" + TextBox2.Text + "=" + Label1.Text + " ";
출력은 다음과 같습니다
20 + 20 = 40 40 + 20 = 60 60 + 20 = 80
계산이 포함 된 문자열이 있습니다. 각 항목은 다음 항목 사이에 공백이 있습니다. 최근 20 개의 항목 만 보관하려면 어떻게합니까?문자열의 처음 20 개 항목 만 유지하십시오.
Label2.text += TextBox1.Text + "+" + TextBox2.Text + "=" + Label1.Text + " ";
출력은 다음과 같습니다
20 + 20 = 40 40 + 20 = 60 60 + 20 = 80
string.Split(' ').Reverse().Take(20)
또는 다윗 & Groo 다른 의견은 "가장 최근"간주되는
string.Split(' ').Reverse().Take(20).Reverse()
가장 최근의가에있는 경우 문자열
string.Split(' ').Take(20)
을 분할 사용 끝까지 사용하면 OrderByDescending
을 사용할 수 있습니다. Take20
string.Split(' ').Select((n, i) => new { Value = n, Index = i }).OrderByDescending(i => i.Index).Take(20);
(210)
.. 배열을 가져오고 가장 최근에 입력하지 않은 처음 20 개를 취합니다. 2 –
'가장 최근'의 의미를 정의 할 수 있습니까? 이게 문자열의 끝인가요? – happygilmore
'string.Split (''). 역행(). Take (20)'? – paul
string[] calculations = yourString.Split(' ');
string[] last20 = calculations.Skip(Math.Max(0, calculations.Count() - 20).Take(20);
는
:
// have a field which will contain calculations
Queue<string> calculations = new Queue<string>();
void OnNewEntryAdded(string entry)
{
// add the entry to the end of the queue...
calculations.Enqueue(entry);
// ... then trim the beginning of the queue ...
while (calculations.Count > 20)
calculations.Dequeue();
// ... and then build the final string
Label2.text = string.Join(" ", calculations);
}
참고 while
루프가 아마 한 번만 실행 한 것을 쉽게 교체 할 수 있습니다 if
(단, 큐가 여러 위치에서 업데이트되는 경우에는 안전 장치 일뿐입니다).
또한 Label
이 실제로 항목 목록을 유지하는 데 적합한 컨트롤인지 궁금합니다.
+1 효율성을 위해이 답변을 정말 좋아합니다. – itsme86
지적대로? – MikeSmithDev
최신 항목은 마지막에 붙습니다. – rupes0610