本文整理汇总了C#中String.Split方法的典型用法代码示例。如果您正苦于以下问题:C# String.Split方法的具体用法?C# String.Split怎么用?C# String.Split使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类String
的用法示例。
在下文中一共展示了String.Split方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SplitURLIntoParts
private static IEnumerable<KeyValuePair<String, String>> SplitURLIntoParts(String magnetLink)
{
String[] parts = magnetLink.Split('&');
ICollection<KeyValuePair<String, String>> values = new Collection<KeyValuePair<string, string>>();
foreach (String str in parts)
{
String[] kv = str.Split('=');
values.Add(new KeyValuePair<string, string>(kv[0], Uri.UnescapeDataString(kv[1])));
}
return values;
}
示例2: Matches
public static Boolean Matches(String source, String target)
{
if (String.IsNullOrWhiteSpace(source))
{
throw new ArgumentNullException("source");
}
if (String.IsNullOrWhiteSpace(target))
{
throw new ArgumentNullException("target");
}
Boolean found = false;
foreach (String pattern in source.Split(' '))
{
if (s_ignoredItems.Contains(pattern.ToUpperInvariant()))
{
continue;
}
BoyerMoore matcher = new BoyerMoore(pattern);
foreach (String actual in target.Split(' '))
{
if (matcher.TurboBoyerMooreMatch(actual).Count() > 0)
{
found = true;
}
else
{
Int32 dist = LevenshteinDistance.Compute(pattern, actual);
if (dist == 1 && (pattern.Length == actual.Length))
{
found = true;
}
else if (dist <= pattern.Length - actual.Length)
{
found = true;
}
else
{
found = false;
}
}
}
}
return found;
}
示例3: EasyMessage
// unserialize
public EasyMessage(String serialized)
{
var parts = serialized.Split(':');
if(parts.Length < 4)
{
throw new Exception("Error unserializing message.");
}
int numberInGrid = Convert.ToInt32(System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(parts[0])));
var blocks = new List<IMyTerminalBlock>();
EasyAPI.grid.GetBlocksOfType<IMyProgrammableBlock>(blocks, delegate(IMyTerminalBlock block) {
return (block as IMyProgrammableBlock).NumberInGrid == numberInGrid;
});
if(blocks.Count == 0)
{
throw new Exception("Message sender no longer exits!");
}
this.From = new EasyBlock((IMyTerminalBlock)blocks[0]);
this.Subject = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(parts[1]));
this.Message = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(parts[2]));
this.Timestamp = Convert.ToInt64(System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(parts[3])));
}
示例4: CreateSeparatedString
private ArrayList CreateSeparatedString( String directory )
{
ArrayList list = new ArrayList();
if (directory == null || directory.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
String[] separatedArray = directory.Split( m_separators );
for (int index = 0; index < separatedArray.Length; ++index)
{
if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
{
if (index < 2 &&
directory[index] == '/')
{
list.Add( '/' );
}
else if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
}
else if (separatedArray[index].Equals( "*" ))
{
if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
list.Add( separatedArray[index] );
}
else
{
list.Add( separatedArray[index] );
}
}
return list;
}
示例5: MessageType
public MessageType(String name, String block)
{
this.Name = name.Substring("Message".Length);
String[] rules = block.Split(';');
if (rules.Length < 1)
{
Field rule = new Field(block + ";");
this.rules.Add(rule);
}
foreach (String _rule in rules)
{
Field rule = new Field(_rule + ";");
this.rules.Add(rule);
}
}
示例6: Parse
// Parse a string into a TimeSpan value.
public static TimeSpan Parse (String s)
{
long numberofticks = 0;
int days = 0, hours, minutes, seconds;
long fractions;
int fractionslength = 0;
String fractionss = String.Empty;
String[] tempstringarray;
bool minus = false;
//Precheck for null reference
if (s == null)
{
throw new ArgumentNullException("s", _("Arg_NotNull"));
}
try
{
//Cut of whitespace and check for minus specifier
s = s.Trim();
minus = s.StartsWith("-");
//Get days if present
if ((s.IndexOf(".") < s.IndexOf(":")) && (s.IndexOf(".") != -1))
{
days = Int32.Parse(s.Substring(0, s.IndexOf(".")));
s = s.Substring(s.IndexOf(".") + 1);
}
//Get fractions if present
if ((s.IndexOf(".") > s.IndexOf(":")) && (s.IndexOf(".") != -1))
{
fractionss = s.Substring(s.IndexOf(".") + 1);
fractionslength = fractionss.Length;
s = s.Substring(0, s.IndexOf("."));
}
//Parse the hh:mm:ss string
tempstringarray = s.Split(':');
hours = Int32.Parse(tempstringarray[0]);
minutes = Int32.Parse(tempstringarray[1]);
seconds = Int32.Parse(tempstringarray[2]);
}
catch
{
throw new FormatException(_("Exception_Format"));
}
//Check for overflows
if ( ((hours > 23) || (hours < 0)) ||
((minutes > 59) || (minutes < 0)) ||
((seconds > 59) || (seconds < 0)) ||
((fractionslength > 7) || (fractionslength < 1)) )
{
throw new OverflowException(_("Arg_DateTimeRange"));
}
//Calculate the fractions expressed in a second
if(fractionss != String.Empty)
{
fractions = Int32.Parse(fractionss) * TicksPerSecond;
while(fractionslength > 0)
{
fractions /= 10;
--fractionslength;
}
}
else
{
fractions = 0;
}
//Calculate the numberofticks
numberofticks += (days * TicksPerDay);
numberofticks += (hours * TicksPerHour);
numberofticks += (minutes * TicksPerMinute);
numberofticks += (seconds * TicksPerSecond);
numberofticks += fractions;
//Apply the minus specifier
if (minus == true) numberofticks = 0 - numberofticks;
//Last check
if ((numberofticks < MinValue.Ticks) || (numberofticks > MaxValue.Ticks))
{
throw new OverflowException(_("Arg_DateTimeRange"));
}
//Return
return new TimeSpan(numberofticks);
}
示例7: AddDefines
// Add a list of "csc" defines to a "cscc" command-line.
private static void AddDefines(ref String[] args, String defines)
{
if(defines != String.Empty)
{
String[] defs = defines.Split(',', ';');
foreach(String def in defs)
{
AddArgument(ref args, "-D" + def);
}
}
}
示例8: GetEraFromValue
//
// GetEraFromValue
//
// Parse the registry value name/data pair into an era
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
private static EraInfo GetEraFromValue(String value, String data)
{
// Need inputs
if (value == null || data == null) return null;
//
// Get Date
//
// Need exactly 10 characters in name for date
// yyyy.mm.dd although the . can be any character
if (value.Length != 10) return null;
int year;
int month;
int day;
if (!Int32.TryParse(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
!Int32.TryParse(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
!Int32.TryParse(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
{
// Couldn't convert integer, fail
return null;
}
//
// Get Strings
//
// Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
String[] names = data.Split(new char[] {'_'});
// Should have exactly 4 parts
// 0 - Era Name
// 1 - Abbreviated Era Name
// 2 - English Era Name
// 3 - Abbreviated English Era Name
if (names.Length != 4) return null;
// Each part should have data in it
if (names[0].Length == 0 ||
names[1].Length == 0 ||
names[2].Length == 0 ||
names[3].Length == 0)
return null;
//
// Now we have an era we can build
// Note that the era # and max era year need cleaned up after sorting
// Don't use the full English Era Name (names[2])
//
return new EraInfo( 0, year, month, day, year - 1, 1, 0,
names[0], names[1], names[3]);
}
示例9: ParseRawMessage
public void ParseRawMessage(String raw)
{
char[] m_seps = { '\n' };
char[] m_hseps = { ':' };
char[] m_cseps = { ';' };
Raw = raw;
String[] m_lines = raw.Split(m_seps);
for (int x = 0; x < m_lines.Length; x++)
{
m_lines[x] = m_lines[x].TrimEnd('\r');
}
String m_current_header = "";
int i = 0;
for (i = 0; i < m_lines.Length; i++)
{
if (m_lines[i].Trim().Length == 0) break;
m_current_header = m_lines[i].Trim();
while (m_lines[i + 1].StartsWith("\t") || m_lines[i + 1].StartsWith(" "))
{
m_current_header = m_current_header.Trim() + " " + m_lines[++i].Trim();
}
String[] m_part = m_current_header.Split(m_hseps, 2);
Headers.Add(new Pop3Header(m_part[0], m_part[1].Trim()));
}
//find some special headers to make them easier to use
foreach (Pop3Header h in Headers)
{
if (h.Name.ToLower() == "subject")
{
Subject = h.Value;
}
else if (h.Name.ToLower() == "to")
{
To = h.Value;
}
else if (h.Name.ToLower() == "from")
{
From = h.Value;
}
else if (h.Name.ToLower() == "reply-to")
{
ReplyTo = h.Value;
}
else if (h.Name.ToLower() == "mime-version")
{
double tmp;
if (double.TryParse(h.Value, out tmp))
{
MimeVersion = tmp;
}
}
else if (h.Name.ToLower() == "date")
{
try
{
Date = DateTime.Parse(h.Value);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
Date = DateTime.Now;
}
}
else if (h.Name.ToLower() == "content-type")
{
String m_type = h.Value;
if (m_type.Contains(";"))
{
//ContentBoundary
String[] m_cparts = m_type.Split(m_cseps);
ContentType = m_cparts[0];
for (int x = 1; x < m_cparts.Length; x++)
{
m_cparts[x] = m_cparts[x].Trim();
if (m_cparts[x].StartsWith("boundary=\""))
{
ContentBoundary = m_cparts[x].Substring(10, m_cparts[x].Length - 11);
}
else if (m_cparts[x].StartsWith("boundary"))
{
ContentBoundary = m_cparts[x].Substring(9, m_cparts[x].Length - 9);
}
}
}
else
{
ContentType = h.Value;
}
//.........这里部分代码省略.........
示例10: SplitFilter
// Split a filter string into a list of names and extensions.
private void SplitFilter(String filter)
{
// Split the filter string into its components and
// then check that we have an even number of components.
String[] split = filter.Split('|');
if(split.Length == 0 || (split.Length % 2) != 0)
{
throw new ArgumentException
(S._("SWF_FileDialog_Filter"));
}
// Create the filter name and pattern arrays.
int len = split.Length / 2;
int posn;
String[] names = new String [len];
String[] patterns = new String [len];
for(posn = 0; posn < len; ++posn)
{
names[posn] = split[posn * 2];
patterns[posn] = split[posn * 2 + 1].ToLower();
if(patterns[posn] == String.Empty)
{
throw new ArgumentException
(S._("SWF_FileDialog_Filter"));
}
}
filterNames = names;
filterPatterns = patterns;
if(filterIndex > len)
{
filterIndex = 1;
}
// Set the default filter index if "DefaultExt" is non-empty.
if(defaultExt.Length > 0 && defaultExt[0] == '.' &&
filterNames.Length > 1 && !filterIndexSet)
{
SetDefaultFilterIndex();
}
}
示例11: IsCustomAttributeOfType
//
// Lightweight check to see if a custom attribute's is of a well-known type.
//
// This check performs without instantating the Type object and bloating memory usage. On the flip side,
// it doesn't check on whether the type is defined in a paricular assembly. The desktop CLR typically doesn't
// check this either so this is useful from a compat persective as well.
//
public static bool IsCustomAttributeOfType(this CustomAttributeHandle customAttributeHandle,
MetadataReader reader,
String ns,
String name)
{
String[] namespaceParts = ns.Split('.');
Handle typeHandle = customAttributeHandle.GetCustomAttribute(reader).GetAttributeTypeHandle(reader);
HandleType handleType = typeHandle.HandleType;
if (handleType == HandleType.TypeDefinition)
{
TypeDefinition typeDefinition = typeHandle.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader);
if (!typeDefinition.Name.StringEquals(name, reader))
return false;
NamespaceDefinitionHandle nsHandle = typeDefinition.NamespaceDefinition;
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceDefinition namespaceDefinition = nsHandle.GetNamespaceDefinition(reader);
if (!namespaceDefinition.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceDefinition.ParentScopeOrNamespace.IsNamespaceDefinitionHandle(reader))
return false;
nsHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader);
}
if (!nsHandle.GetNamespaceDefinition(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else if (handleType == HandleType.TypeReference)
{
TypeReference typeReference = typeHandle.ToTypeReferenceHandle(reader).GetTypeReference(reader);
if (!typeReference.TypeName.StringEquals(name, reader))
return false;
if (!typeReference.ParentNamespaceOrType.IsNamespaceReferenceHandle(reader))
return false;
NamespaceReferenceHandle nsHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(reader);
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceReference namespaceReference = nsHandle.GetNamespaceReference(reader);
if (!namespaceReference.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceReference.ParentScopeOrNamespace.IsNamespaceReferenceHandle(reader))
return false;
nsHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader);
}
if (!nsHandle.GetNamespaceReference(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else
throw new NotSupportedException();
}
示例12: processMsg
public void processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived)
{
// Handle the message received and
// send a response back to the client.
mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);
mscClient = client;
for (int i = 0; i < mstrMessage.Length && mstrMessage[i] != '\0'; i++)
{
buffer.push_back(mstrMessage[i]);
}
while (!buffer.empty())
{
if (insidebraces)
{
if (buffer.front() == '}')
{
insidebraces = false;
//handle l, r presses
if (temp2.v[0] == 'p' && temp2.v[1] == 'l')
{
Console.WriteLine("left pressed");
VirtualKeyboard.KeyDown(Keys.Left);
}
else if (temp2.v[0] == 'r' && temp2.v[1] == 'l')
{
Console.WriteLine("left released");
VirtualKeyboard.KeyUp(Keys.Left);
}
else if (temp2.v[0] == 'p' && temp2.v[1] == 'r')
{
Console.WriteLine("right pressed");
VirtualKeyboard.KeyDown(Keys.Right);
}
else if (temp2.v[0] == 'r' && temp2.v[1] == 'r')
{
Console.WriteLine("right released");
VirtualKeyboard.KeyUp(Keys.Right);
}
temp2.clear();
}
else
{
temp2.push_back(buffer.front());
}
buffer.pop_front();
}
else
{
if (buffer.front() == '{')
{
insidebraces = true;
}
else
{
temp.push_back(buffer.front());
if (temp.back() == '#') hashes++;
}
buffer.pop_front();
if (hashes == 3) break;
}
}
if (hashes < 3)
{
return;
}
mstrMessage = new String(temp.v, 0, temp.length);
hashes = 0;
temp.clear();
//mstrMessage = mstrMessage.Substring(0, 5);
//return;
//float x;
char[] sep = new char[1];
sep[0] = '#';
string[] scoms = mstrMessage.Split(sep);
float[] fcoms = new float[3];
bool[] pos = new bool[3];
pos[0] = float.TryParse(scoms[0], out fcoms[0]);
pos[1] = float.TryParse(scoms[1], out fcoms[1]);
pos[2] = float.TryParse(scoms[2], out fcoms[2]);
//Console.WriteLine(x);
float sensitivityV = 0.08f;
float sensitivityH = 0.05f;
ControllerA.intensity = (Math.Abs(fcoms[2]) - sensitivityV) * 0.5f;
ControllerA.max_intensity = (Math.Abs(0.6f) - sensitivityV) * 0.5f;
ControllerZ.intensity = (Math.Abs(fcoms[2]) - sensitivityV) * 0.5f;
ControllerZ.max_intensity = (Math.Abs(0.6f) - sensitivityV) * 0.5f;
ControllerL.intensity = (Math.Abs(fcoms[1]) - sensitivityH) * 1f;
ControllerL.max_intensity = (Math.Abs(0.6f) - sensitivityH) * 0.5f;
//.........这里部分代码省略.........
示例13: GetUsernameComponents
/// <summary>
/// Returns a String[] with format { username, domain } for the users currently selected username.
/// </summary>
/// <returns>A String[] with format { username, domain }.</returns>
private String[] GetUsernameComponents(String username)
{
String domain = String.Empty;
String[] usernameParts;
// Auto-populate domain field if domain specified in username as DOMAIN\user
usernameParts = username.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
if (usernameParts.Length == 2)
{
username = usernameParts[1];
domain = usernameParts[0];
}
// Auto-populate domain field if domain specified in username as [email protected]
usernameParts = this.txtUserName.Text.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
if (usernameParts.Length == 2)
{
username = usernameParts[0];
domain = usernameParts[1];
}
return new String[] { username, domain };
}
示例14: ValidateProperty
public static bool ValidateProperty(String propertyName, String propertyValue)
{
bool isPropertyValid = true;
if (propertyName.Equals("enabled") || propertyName.Equals("visible"))
{
bool val;
if (!Boolean.TryParse(propertyValue, out val)) isPropertyValid = false;
}
else if (propertyName.Equals("backgroundColor"))
{
try
{
System.Windows.Media.SolidColorBrush brush;
MoSync.Util.ConvertStringToColor(propertyValue, out brush);
}
catch (InvalidPropertyValueException)
{
isPropertyValid = false;
}
}
else if (propertyName.Equals("backgroundGradient"))
{
try
{
System.Windows.Media.GradientStop firstGradientStop = new System.Windows.Media.GradientStop();
System.Windows.Media.GradientStop secondGradientStop = new System.Windows.Media.GradientStop();
System.Windows.Media.SolidColorBrush firstBrush;
Util.ConvertStringToColor(propertyValue.Split(',')[0], out firstBrush);
System.Windows.Media.SolidColorBrush secondBrush;
Util.ConvertStringToColor(propertyValue.Split(',')[1], out secondBrush);
}
catch (InvalidPropertyValueException)
{
isPropertyValid = false;
}
}
return isPropertyValid;
}
示例15: GetAllFiles
/// <summary>获取目录内所有符合条件的文件,支持多文件扩展匹配</summary>
/// <param name="di">目录</param>
/// <param name="exts">文件扩展列表。比如*.exe;*.dll;*.config</param>
/// <param name="allSub">是否包含所有子孙目录文件</param>
/// <returns></returns>
public static IEnumerable<FileInfo> GetAllFiles(this DirectoryInfo di, String exts = null, Boolean allSub = false)
{
if (di == null || !di.Exists) yield break;
if (String.IsNullOrEmpty(exts)) exts = "*";
var opt = allSub ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var pattern in exts.Split(";", "|", ","))
{
foreach (var item in di.GetFiles(pattern, opt))
{
yield return item;
}
}
}