本文整理汇总了C#中String.Trim方法的典型用法代码示例。如果您正苦于以下问题:C# String.Trim方法的具体用法?C# String.Trim怎么用?C# String.Trim使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类String
的用法示例。
在下文中一共展示了String.Trim方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Parse
// String parsing.
public static bool Parse(String value)
{
if(value != null)
{
if(String.Compare(value, TrueString, true) == 0)
{
return true;
}
else if(String.Compare(value, FalseString, true) == 0)
{
return false;
}
value = value.Trim();
if(String.Compare(value, TrueString, true) == 0)
{
return true;
}
else if(String.Compare(value, FalseString, true) == 0)
{
return false;
}
throw new FormatException(_("Format_BadBoolean"));
}
else
{
throw new ArgumentNullException("value");
}
}
示例2: ToSlug
public static String ToSlug(String url)
{
if (string.IsNullOrWhiteSpace(url)) return "";
url = Regex.Replace(url, "[áàảãạâấầẩẫậăắằẳẵặ]", "a", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[đ]", "d", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[éèẻẽẹêếềểễệ]", "e", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[íìỉĩị]", "i", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[óòỏõọôốồổỗộơớờởỡợ]", "o", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[ýỳỷỹỵ]", "y", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[úùủũụưứừửữự]", "u", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "\\s+", "-", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[^a-z0-9-]", "-", RegexOptions.Compiled | RegexOptions.IgnoreCase);
url = Regex.Replace(url, "[-]+", "-", RegexOptions.Compiled | RegexOptions.IgnoreCase);
return url.Trim('-', ' ');
}
示例3: CreateRegexPattern
public String CreateRegexPattern(String fieldSpecification)
{
//masterPattern is going to hold a "big" regex pattern
/// that will be ran against the original text
string masterPattern = fieldSpecification.Trim();
//Replace all of the types with the pattern
//that matches that type
masterPattern = Regex.Replace(masterPattern, @"\{String\}",
(String)typePatterns["String"]);
masterPattern = Regex.Replace(masterPattern, @"\{Int16\}",
(String)typePatterns["Int16"]);
masterPattern = Regex.Replace(masterPattern, @"\{UInt16\}",
(String)typePatterns["UInt16"]);
masterPattern = Regex.Replace(masterPattern, @"\{Int32\}",
(String)typePatterns["Int32"]);
masterPattern = Regex.Replace(masterPattern, @"\{UInt32\}",
(String)typePatterns["UInt32"]);
masterPattern = Regex.Replace(masterPattern, @"\{Int64\}",
(String)typePatterns["Int64"]);
masterPattern = Regex.Replace(masterPattern, @"\{UInt64\}",
(String)typePatterns["UInt64"]);
masterPattern = Regex.Replace(masterPattern, @"\{Single\}",
(String)typePatterns["Single"]);
masterPattern = Regex.Replace(masterPattern, @"\{Double\}",
(String)typePatterns["Double"]);
masterPattern = Regex.Replace(masterPattern, @"\{Boolean\}",
(String)typePatterns["Boolean"]);
masterPattern = Regex.Replace(masterPattern, @"\{Byte\}",
(String)typePatterns["Byte"]);
masterPattern = Regex.Replace(masterPattern, @"\{SByte\}",
(String)typePatterns["SByte"]);
masterPattern = Regex.Replace(masterPattern, @"\{Char\}",
(String)typePatterns["Char"]);
masterPattern = Regex.Replace(masterPattern, @"\{Decimal\}",
(String)typePatterns["Decimal"]);
masterPattern = Regex.Replace(masterPattern, @"\s+", "\\s+");
//replace the white space with the pattern for white space
return masterPattern;
}
示例4: ParseMultiValue
/// <summary>
/// Parses single HTTP header and separates values delimited by comma.
/// Like "Content-Type: text, HTML". The value string "text, HTML" will se parsed into 2 strings.
/// </summary>
/// <param name="value">Value string with possible multivalue</param>
/// <returns>Array of strings with single value in each. </returns>
private static string[] ParseMultiValue(string value)
{
ArrayList tempCollection = new ArrayList();
bool inquote = false;
int chIndex = 0;
char[] vp = new char[value.Length];
string singleValue;
for (int i = 0; i < value.Length; i++)
{
if (value[i] == '\"')
{
inquote = !inquote;
}
else if ((value[i] == ',') && !inquote)
{
singleValue = new String(vp, 0, chIndex);
tempCollection.Add(singleValue.Trim());
chIndex = 0;
continue;
}
vp[chIndex++] = value[i];
}
//
// Now add the last of the header values to the stringtable.
//
if (chIndex != 0)
{
singleValue = new String(vp, 0, chIndex);
tempCollection.Add(singleValue.Trim());
}
return (string[])tempCollection.ToArray(typeof(string));
}
示例5: ParseMultiValue
//
//
private static string[] ParseMultiValue(string value) {
StringCollection tempStringCollection = new StringCollection();
bool inquote = false;
int chIndex = 0;
char[] vp = new char[value.Length];
string singleValue;
for (int i = 0; i < value.Length; i++) {
if (value[i] == '\"') {
inquote = !inquote;
}
else if ((value[i] == ',') && !inquote) {
singleValue = new String(vp, 0, chIndex);
tempStringCollection.Add(singleValue.Trim());
chIndex = 0;
continue;
}
vp[chIndex++] = value[i];
}
//
// Now add the last of the header values to the stringtable.
//
if (chIndex != 0) {
singleValue = new String(vp, 0, chIndex);
tempStringCollection.Add(singleValue.Trim());
}
string[] stringArray = new string[tempStringCollection.Count];
tempStringCollection.CopyTo(stringArray, 0) ;
return stringArray;
}
示例6: Unquote
internal static string Unquote (String str) {
int start = str.IndexOf ('\"');
int end = str.LastIndexOf ('\"');
if (start >= 0 && end >=0)
str = str.Substring (start + 1, end - 1);
return str.Trim ();
}
示例7: ParseSingle
internal unsafe static Single ParseSingle(String value, NumberStyles options, IFormatProvider provider)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
NumberFormatInfo numfmt = provider == null ? NumberFormatInfo.CurrentInfo : NumberFormatInfo.GetInstance(provider);
NumberBuffer number = new NumberBuffer();
Double d = 0;
if (!TryStringToNumber(value, options, ref number, numfmt, false))
{
//If we failed TryStringToNumber, it may be from one of our special strings.
//Check the three with which we're concerned and rethrow if it's not one of
//those strings.
String sTrim = value.Trim();
if (sTrim.Equals(numfmt.PositiveInfinitySymbol))
{
return Single.PositiveInfinity;
}
if (sTrim.Equals(numfmt.NegativeInfinitySymbol))
{
return Single.NegativeInfinity;
}
if (sTrim.Equals(numfmt.NaNSymbol))
{
return Single.NaN;
}
throw new FormatException(SR.Format_InvalidString);
}
if (!NumberBufferToDouble(number, ref d))
{
throw new OverflowException(SR.Overflow_Single);
}
Single castSingle = (Single)d;
if (Single.IsInfinity(castSingle))
{
throw new OverflowException(SR.Overflow_Single);
}
return castSingle;
}
示例8: InsertHash
private void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue)
{
// The month of the 13th month is allowed to be null, so make sure that we ignore null value here.
if (str == null || str.Length == 0)
{
return;
}
TokenHashValue value;
int i = 0;
// If there is whitespace characters in the beginning and end of the string, trim them since whitespaces are skipped by
// DateTime.Parse().
if (Char.IsWhiteSpace(str[0]) || Char.IsWhiteSpace(str[str.Length - 1]))
{
str = str.Trim(null); // Trim white space characters.
// Could have space for separators
if (str.Length == 0)
return;
}
char ch = this.Culture.TextInfo.ToLower(str[0]);
int hashcode = ch % TOKEN_HASH_SIZE;
int hashProbe = 1 + ch % SECOND_PRIME;
do
{
value = hashTable[hashcode];
if (value == null)
{
//// Console.WriteLine(" Put Key: {0} in {1}", str, hashcode);
hashTable[hashcode] = new TokenHashValue(str, tokenType, tokenValue);
return;
}
else
{
// Collision happens. Find another slot.
if (str.Length >= value.tokenString.Length)
{
// If there are two tokens with the same prefix, we have to make sure that the longer token should be at the front of
// the shorter ones.
if (this.Culture.CompareInfo.Compare(str, 0, value.tokenString.Length, value.tokenString, 0, value.tokenString.Length, CompareOptions.IgnoreCase) == 0)
{
if (str.Length > value.tokenString.Length)
{
// The str to be inserted has the same prefix as the current token, and str is longer.
// Insert str into this node, and shift every node behind it.
InsertAtCurrentHashNode(hashTable, str, ch, tokenType, tokenValue, i, hashcode, hashProbe);
return;
}
else
{
// Same token. If they have different types (regular token vs separator token). Add them.
// If we have the same regular token or separator token in the hash already, do NOT update the hash.
// Therefore, the order of inserting token is significant here regarding what tokenType will be kept in the hash.
//
// Check the current value of RegularToken (stored in the lower 8-bit of tokenType) , and insert the tokenType into the hash ONLY when we don't have a RegularToken yet.
// Also check the current value of SeparatorToken (stored in the upper 8-bit of token), and insert the tokenType into the hash ONLY when we don't have the SeparatorToken yet.
//
int nTokenType = (int)tokenType;
int nCurrentTokenTypeInHash = (int)value.tokenType;
//
// The folowing is the fix for the issue of throwing FormatException when "mar" is passed in string of the short date format dd/MMM/yyyy for es-MX
//
if (((nCurrentTokenTypeInHash & (int)TokenType.RegularTokenMask) == 0) && ((nTokenType & (int)TokenType.RegularTokenMask) != 0) ||
((nCurrentTokenTypeInHash & (int)TokenType.SeparatorTokenMask) == 0) && ((nTokenType & (int)TokenType.SeparatorTokenMask) != 0))
{
value.tokenType |= tokenType;
if (tokenValue != 0)
{
value.tokenValue = tokenValue;
}
}
// The token to be inserted is already in the table. Skip it.
}
}
}
}
//// Console.WriteLine(" COLLISION. Old Key: {0}, New Key: {1}", hashTable[hashcode].tokenString, str);
i++;
hashcode += hashProbe;
if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
} while (i < TOKEN_HASH_SIZE);
Debug.Assert(true, "The hashtable is full. This should not happen.");
}
示例9: 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);
}
示例10: sendCommand
/// <summary>
/// sendCommand
/// </summary>
/// <param name="command"></param>
private void sendCommand(String command)
{
int l_iRetval = 0;
if (this.verboseDebugging)
{
if (command.IndexOf("PASS ") >= 0)
{
// don't show password in message area
// show only *
showMessage("PASS [*** hidden ***]", false);
}
else
{
showMessage(command, false);
}
}
try
{
Byte[] cmdBytes = Encoding.ASCII.GetBytes((command.Trim() + "\r\n").ToCharArray());
l_iRetval = clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
this.readResponse();
}
catch (Exception ex)
{
throw new IOException(ex.Message);
}
}
示例11: AppendQuoted
private static void AppendQuoted(this StringBuilder sb, String s)
{
bool needsQuoting = false;
const char quoteChar = '\"';
//@todo: App-compat: You can use double or single quotes to quote a name, and Fusion (or rather the IdentityAuthority) picks one
// by some algorithm. Rather than guess at it, I'll just use double-quote consistently.
if (s != s.Trim() || s.Contains("\"") || s.Contains("\'"))
needsQuoting = true;
if (needsQuoting)
sb.Append(quoteChar);
for (int i = 0; i < s.Length; i++)
{
bool addedEscape = false;
foreach (KeyValuePair<char, String> kv in AssemblyNameLexer.EscapeSequences)
{
String escapeReplacement = kv.Value;
if (!(s[i] == escapeReplacement[0]))
continue;
if ((s.Length - i) < escapeReplacement.Length)
continue;
String prefix = s.Substring(i, escapeReplacement.Length);
if (prefix == escapeReplacement)
{
sb.Append('\\');
sb.Append(kv.Key);
addedEscape = true;
}
}
if (!addedEscape)
sb.Append(s[i]);
}
if (needsQuoting)
sb.Append(quoteChar);
}
示例12: GetNext
//
// Return the next token in assembly name. If the result is DisplayNameToken.String,
// sets "tokenString" to the tokenized string.
//
internal Token GetNext(out String tokenString)
{
tokenString = null;
while (Char.IsWhiteSpace(_chars[_index]))
_index++;
char c = _chars[_index++];
if (c == 0)
return Token.End;
if (c == ',')
return Token.Comma;
if (c == '=')
return Token.Equals;
StringBuilder sb = new StringBuilder();
char quoteChar = (char)0;
if (c == '\'' || c == '\"')
{
quoteChar = c;
c = _chars[_index++];
}
for (; ;)
{
if (c == 0)
{
_index--;
break; // Terminate: End of string (desktop compat: if string was quoted, permitted to terminate without end-quote.)
}
if (quoteChar != 0 && c == quoteChar)
break; // Terminate: Found closing quote of quoted string.
if (quoteChar == 0 && (c == ',' || c == '='))
{
_index--;
break; // Terminate: Found start of a new ',' or '=' token.
}
if (quoteChar == 0 && (c == '\'' || c == '\"'))
throw new FileLoadException(); // Desktop compat: Unescaped quote illegal unless entire string is quoted.
if (c == '\\')
{
c = _chars[_index++];
bool matched = false;
foreach (KeyValuePair<char, String> kv in EscapeSequences)
{
if (c == kv.Key)
{
matched = true;
sb.Append(kv.Value);
break;
}
}
if (!matched)
throw new FileLoadException(); // Unrecognized escape
}
else
{
sb.Append(c);
}
c = _chars[_index++];
}
tokenString = sb.ToString();
if (quoteChar == 0)
tokenString = tokenString.Trim(); // Unless quoted, whitespace at beginning or end doesn't count.
return Token.String;
}
示例13: TryParse
public static bool TryParse(String value, out bool result)
{
result = false;
if(value != null)
{
value = value.Trim();
if (String.Compare(value, TrueString, true) == 0)
{
result = true;
return true;
}
else if (String.Compare(value, FalseString, true) == 0)
{
result = false;
return true;
}
}
return false;
}
示例14: TryParseTimeSpan
// ---- SECTION: private static methods that do the actual work ---------*
#region TryParseTimeSpan
//
// TryParseTimeSpan
//
// Actions: Common private Parse method called by both Parse and TryParse
//
private static Boolean TryParseTimeSpan(String input, TimeSpanStandardStyles style, IFormatProvider formatProvider, ref TimeSpanResult result)
{
if (input == null)
{
result.SetFailure(ParseFailureKind.ArgumentNull, SR.ArgumentNull_String, null, "input");
return false;
}
input = input.Trim();
if (input == String.Empty)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_BadTimeSpan);
return false;
}
TimeSpanTokenizer tokenizer = new TimeSpanTokenizer();
tokenizer.Init(input);
TimeSpanRawInfo raw = new TimeSpanRawInfo();
raw.Init(DateTimeFormatInfo.GetInstance(formatProvider));
TimeSpanToken tok = tokenizer.GetNextToken();
/* The following loop will break out when we reach the end of the str or
* when we can determine that the input is invalid. */
while (tok.ttt != TTT.End)
{
if (!raw.ProcessToken(ref tok, ref result))
{
result.SetFailure(ParseFailureKind.Format, SR.Format_BadTimeSpan);
return false;
}
tok = tokenizer.GetNextToken();
}
if (!tokenizer.EOL)
{
// embedded nulls in the input string
result.SetFailure(ParseFailureKind.Format, SR.Format_BadTimeSpan);
return false;
}
if (!ProcessTerminalState(ref raw, style, ref result))
{
result.SetFailure(ParseFailureKind.Format, SR.Format_BadTimeSpan);
return false;
}
return true;
}
示例15: FindCommandType
// 对FTP命令进行分类
public static FtpCommandType FindCommandType(String szCommand)
{
if (szCommand == null)
szCommand = "";
szCommand = szCommand.Trim();
szCommand = szCommand.ToUpper();
if (szCommand.Equals("USER")
|| szCommand.Equals("PASS")
|| szCommand.Equals("CWD")
|| szCommand.Equals("PWD")
|| szCommand.Equals("CDUP")
|| szCommand.Equals("DELE")
|| szCommand.Equals("MKD")
|| szCommand.Equals("RMD")
|| szCommand.Equals("REN")
|| szCommand.Equals("RNFR")
|| szCommand.Equals("RNTO")
|| szCommand.Equals("QUIT"))
return FtpCommandType.FtpControlCommand;
else if (szCommand.Equals("RETR")
|| szCommand.Equals("LIST"))
return FtpCommandType.FtpDataReceiveCommand;
else if (szCommand.Equals("STOR")
|| szCommand.Equals("STOU"))
return FtpCommandType.FtpDataSendCommand;
else
return FtpCommandType.FtpCommandNotSupported;
}