3D 프린터를 제어하는 작은 프로그램을 만들고 있습니다. 내가 무언가를 보낼 때 일반적으로으로 응답 ok
하지만 문제가 있으면 다음과 같이 보냅니다.
T:221.0 /220.0 @:0 W:1
적절한 구분 기호가 있으면 쉽게 구문 분석 할 수 있지만 문자열 때문에 공백을 사용하는 것은 신뢰할 수 없습니다 221.0 /220.0
. 결과적으로 공백을 구분자 /220.0
로 사용하면 키-값 쌍으로 취급 될 수 있지만 T
. 나는 모든 콜론의 색인을 얻고 그 뒤에 1 문자를 시작하려고 계획했지만 키 길이도 가변적입니다. 예를 들면 :
T:221.0 /220.0 B@:127 @:0 W:1
B@
이제 2 자 길이입니다.
나는 약간의 조사를했지만 내가 찾은 모든 것에 는 데이터가 있는 URL과 같은 적절한 구분자가 있었다 .
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311161500&cultuur=en-GB&continent=europa
나는 모든 콜론의 색인을 얻은 다음 시작점 역할을 할 콜론이 발견되면 공백을 뒤로 검색 할 계획이었습니다. 마찬가지로 다음 키-값 쌍의 시작 지점은 이전 항목의 끝점 역할을합니다. 그러나 이것이 올바른 접근 방식인지 확실하지 않습니다.
주요 질문 : 적절한 구분 기호없이 문자열을 어떻게 구문 분석합니까? 나는 정말로 특정한 요구 사항이 없습니다. 배열이든 목록이든, 키와 값에 대한 변수를 분리하거나 모든 것을 배열로 밀어 넣어
string[] data = {key1,value1,key2,value2,key3,value3};
업데이트 : 두 번째 예의 키-값 쌍은 다음과 같습니다.
Key:Value
T:221.0 /220.0
B@:127
@:0
W:1
더 많은 샘플 :
T:221.0 /220.0 B:85.7 /120 B@:30W @:0 W:8
Key:Value
T:221.0 /220.0
B:85.7 /120
B@:30W
@:0
W:8
더 복잡한 또 다른 것이 있습니다.
T:171.4 /220.0 B:90.3 /120 T1:171.4 /220.0 B@:30 @:12W W:6
Key:Value
T:171.4 /220.0 // Temperature of first nozzle heater
B:90.3 /120 // Temperature of the hot plate it's printing on
T1:171.4 /220.0 // Temperature of the second nozzle heater if it exists
B@:30 // Raw power consumption of hotbed (unit depends on config)
@:12W // Power of of nozzle in Watts (unit depends on config)
W:6 // Waiting time (in seconds). If the optimal conditions are met and this counts down to zero, printing resumes. Else, reset to 10.
샘플 문자열 시작 부분의 공백은 의도적입니다. 공백으로 시작합니다. 관심있는 사람들을 위해 Marlin 3D 프린팅 펌웨어를 실행하는 Arduino Mega의 답변입니다. 프린터 히터가 아직 압출 될만큼 뜨겁지 않은 경우의 응답입니다.
관련 항목 : 문자열을 구문 분석하여 키-값 쌍을 찾는 방법
이 논리로 갈 것입니다.
암호:
private List<KeyValuePair<string, string>> ParsePrinterResponse(string rawResponse)
{
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();
string[] colonItems = rawResponse.Trim().Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (colonItems.Length > 1)
{
string currentKey = colonItems[0], currentValue = "";
for (int i = 1; i < colonItems.Length; i++)
{
string currentItem = colonItems[i];
int spaceIndex = currentItem.LastIndexOf(" ");
if (spaceIndex < 0)
{
//end of string, whole item is the value
currentValue = currentItem;
}
else
{
//middle of string, left part is value, right part is next key
currentValue = currentItem.Substring(0, spaceIndex);
}
pairs.Add(new KeyValuePair<string, string>(currentKey, currentValue));
currentKey = currentItem.Substring(spaceIndex + 1);
}
}
return pairs;
}
사용 샘플 :
errorBox.Lines = ParsePrinterResponse("T:171.4 /220.0 B:90.3 /120 T1:171.4 /220.0 B@:30 @:12W W:6").ConvertAll(p =>
{
return string.Format("{0}:{1}", p.Key, p.Value);
}).ToArray();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다