다음과 같은 문자열을 구문 분석하려고합니다.
string myString = "Value: 1234567_89042, Value1: gh, Value2: New 1";
이를 위해 다음과 같은 값을 얻으려고 노력하고 있습니다.
1234567_89042
gh
New 1
기술적으로 myString을 배열에 저장 한 다음 구분 기호를 사용하여 문자열을 배열의 다른 세그먼트로 분할하는 솔루션이 있습니다.
string[] words = myString.Split(',', ':', ' ', '_');
Console.WriteLine(myString.First());
int count = 0;
foreach (var word in words)
{
System.Console.WriteLine($"{word}");
count++;
}
나는 그 지정된 값을 얻기 위해 문자열을 배열에 저장하지 않는 방법이 있거나 값을 얻기 위해 배열을 통해 더 파싱해야합니까?
아래 코드를 시도하십시오. 이것이 작동하는지 확인하십시오.
string myString = "Value: 1234567_89042, Value1: gh, Value2: New 1";
string[] str = myString.Split(",");
foreach(string s in str)
{
string s1 = s.Split(":")[1].Trim();
Console.WriteLine(s1);
}
위의 코드를 시도했지만 완벽하게 작동했습니다!
한 가지 더 제안, LINQ를 사용하여 위 코드를 단순화했습니다. 아래를 참조하십시오.
static void Main()
{
string myString = "Value: 1234567_89042, Value1: gh, Value2: New 1";
string[] str = myString.Split(",").Select(c => c.Split(":")[1].Trim()).ToArray();
foreach(string s in str)
{
Console.WriteLine(s);
}
}
이것도 잘 작동합니다!
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다