如何有效地分割带字符的字符串?
一个例子是:
inputString =“ABCDEFGHIJ”,sectionLength = 4,splitChar =' - ',output =“ABCD-EFGH-IJ”
这是我的第一次尝试:我希望在每第n个间隔之后将输入字符串与某些字符分开。我想知道是否有更有效的方法来做到这一点,或者如果我错过了可能失败的东西。我相信开头的If语句应该捕获任何无效的输入,保存null输入。
HttpTransportBindingElement httpBinding = new HttpTransportBindingElement();
EndpointAddress serviceAddress = new EndpointAddress(__url);
TextMessageEncodingBindingElement messegeElement = new TextMessageEncodingBindingElement();
httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest;
messegeElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.WSAddressing10);
CustomBinding bind = new CustomBinding(messegeElement, httpBinding);
ONVIF.onvifMedia.mediaClient mclient = new ONVIF.onvifMedia.mediaClient(bind, serviceAddress);
ONVIF.onvifMedia.StreamSetup streamSetup = new ONVIF.onvifMedia.StreamSetup();
streamSetup.Stream = ONVIF.onvifMedia.StreamType.RTPUnicast;
streamSetup.Transport = new ONVIF.onvifMedia.Transport();
streamSetup.Transport.Protocol = ONVIF.onvifMedia.TransportProtocol.RTSP;
mediaUri uri = new mediaUri();
Profile[] profiles;
log.Debug("Trying to fetch profiles");
profiles = mclient.GetProfiles();
foreach (Profile item in profiles)
{
uri = mclient.GetStreamUri(streamSetup, item.token);
}
答案 0 :(得分:3)
Strings in .NET are immutable。这意味着组合字符串的操作最终会创建一个全新的字符串。
这部分代码
for (subStart = 0 ; (subStart + sectionLength) < end; subStart += sectionLength)
{
returnString = returnString + inputString.Substring(subStart, sectionLength) + splitChar;
}
不断创建新字符串。
相反,请探索StringBuilder的使用。
int estimatedFinalStringLength = 100; // <-- Your estimate here
StringBuilder returnString = new StringBuilder(estimatedFinalStringLength);
for (subStart = 0 ; (subStart + sectionLength) < end; subStart += sectionLength)
{
returnString.Append(inputString.Substring(subStart, sectionLength) + splitChar);
}
return returnString.ToString() + inputString.Substring(subStart, end - subStart);
尽最大努力估计最终字符串的总长度将减少StringBuilder内部执行的缓冲区重新分配的数量。