Here are the examples of the csharp api System.Text.StringBuilder.Append(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
8245 Examples
19
Source : FdbTuple`4.cs
with MIT License
from abdullin
with MIT License
from abdullin
public override string ToString()
{
return new StringBuilder(48).Append('(')
.Append(FdbTuple.Stringify(this.Item1)).Append(", ")
.Append(FdbTuple.Stringify(this.Item2)).Append(", ")
.Append(FdbTuple.Stringify(this.Item3)).Append(", ")
.Append(FdbTuple.Stringify(this.Item4)).Append(')')
.ToString();
}
19
Source : FdbTuple`5.cs
with MIT License
from abdullin
with MIT License
from abdullin
public override string ToString()
{
return new StringBuilder(48).Append('(')
.Append(FdbTuple.Stringify(this.Item1)).Append(", ")
.Append(FdbTuple.Stringify(this.Item2)).Append(", ")
.Append(FdbTuple.Stringify(this.Item3)).Append(", ")
.Append(FdbTuple.Stringify(this.Item4)).Append(", ")
.Append(FdbTuple.Stringify(this.Item5)).Append(')')
.ToString();
}
19
Source : Rope.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public override string ToString()
{
Rope<char> charRope = this as Rope<char>;
if (charRope != null) {
return charRope.ToString(0, this.Length);
} else {
StringBuilder b = new StringBuilder();
foreach (T element in this) {
if (b.Length == 0)
b.Append('{');
else
b.Append(", ");
b.Append(element.ToString());
}
b.Append('}');
return b.ToString();
}
}
19
Source : FdbTuple`3.cs
with MIT License
from abdullin
with MIT License
from abdullin
public override string ToString()
{
return new StringBuilder(32).Append('(')
.Append(FdbTuple.Stringify(this.Item1)).Append(", ")
.Append(FdbTuple.Stringify(this.Item2)).Append(", ")
.Append(FdbTuple.Stringify(this.Item3)).Append(')')
.ToString();
}
19
Source : PhoneGenerator.cs
with MIT License
from abock
with MIT License
from abock
public IEnumerable<string> Generate(IEnumerable<string> args)
{
var builder = new StringBuilder();
foreach (var arg in args)
{
foreach (var c in arg)
builder.Append(Translate(c));
builder.Append('#');
yield return builder.ToString();
builder.Clear();
}
}
19
Source : NGramTokenizer.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public StringBuilder[][] Tokenize(string word)
{
var m = word.Length;
var n = m - 1;
var array = new StringBuilder[m][];
for (int i = 0; i < m; i++)
{
array[i] = new StringBuilder[m];
}
for (int j = 0; j < m; j++)
{
for (var k = 0; k < m; k++)
{
array[j][k] = new StringBuilder();
}
}
for (int j = 0; j < m; j++)
{
var letter = word[j];
for (var k = 0; k <= j; k++)
{
for (int i = j - k; i < n && k < m - i; i++)
{
array[i][k].Append( letter);
}
}
}
array[m- 1][0] = new StringBuilder(word);
return array;
}
19
Source : ConsoleExtensions.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public static string InputPreplacedword(string prompt = "")
{
Console.Write(prompt);
StringBuilder sb = new StringBuilder();
while (true)
{
var key = Console.ReadKey(true);
if (key.Key is ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
sb.Append(key.KeyChar);
}
return sb.ToString();
}
19
Source : Utils.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public static string ToFriendlyString(this TimeSpan value)
{
StringBuilder sb = new StringBuilder();
bool haspre = false;
if (value.Days > 0)
{
sb.Append(string.Format("{0} d", value.Days));
haspre = true;
}
if (value.Hours > 0)
{
if (haspre) sb.Append(' ');
sb.Append(string.Format("{0} h", value.Hours));
haspre = true;
}
if (value.Minutes > 0)
{
if (haspre) sb.Append(' ');
sb.Append(string.Format("{0} min", value.Minutes));
haspre = true;
}
if (value.Seconds > 0)
{
if (haspre) sb.Append(' ');
sb.Append(string.Format("{0} s", value.Seconds));
haspre = true;
}
if (value.Milliseconds > 0)
{
if (haspre) sb.Append(' ');
sb.Append(string.Format("{0} ms", value.Milliseconds));
}
else
{
if (!haspre) sb.Append(string.Format("{0} ms", value.Milliseconds));
}
return sb.ToString();
}
19
Source : StringExtensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static string UpperCamelCaseToDelimiterSeparated(this string upperCamelCase)
{
var stringBuilder = new StringBuilder(upperCamelCase.Length, upperCamelCase.Length * 2);
for (int i = 0; i < upperCamelCase.Length; i++)
{
var @char = upperCamelCase[i];
if (char.IsUpper(@char))
{
if (i != 0) stringBuilder.Append('-');
stringBuilder.Append(char.ToLower(@char));
}
else
{
stringBuilder.Append(@char);
}
}
return stringBuilder.ToString();
}
19
Source : PathExtensions.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public static string SanitizeFilename(this string name)
{
if (name == null) return default(string);
var sb = new StringBuilder();
foreach (var c in name)
{
if (FilenameCharReplace.TryGetValue(c, out var s))
sb.Append(s);
else
sb.Append(c);
}
return sb.ToString();
}
19
Source : Format.cs
with MIT License
from actions
with MIT License
from actions
private Boolean ReadFormatSpecifiers(
String str,
Int32 startIndex,
out String result,
out Int32 rbrace)
{
// No format specifiers
var c = SafeCharAt(str, startIndex);
if (c == '}')
{
result = String.Empty;
rbrace = startIndex;
return true;
}
// Validate starts with ":"
if (c != ':')
{
result = default;
rbrace = default;
return false;
}
// Read the specifiers
var specifiers = new StringBuilder();
var index = startIndex + 1;
while (true)
{
// Validate not the end of the string
if (index >= str.Length)
{
result = default;
rbrace = default;
return false;
}
c = str[index];
// Not right-brace
if (c != '}')
{
specifiers.Append(c);
index++;
}
// Escaped right-brace
else if (SafeCharAt(str, index + 1) == '}')
{
specifiers.Append('}');
index += 2;
}
// Closing right-brace
else
{
result = specifiers.ToString();
rbrace = index;
return true;
}
}
}
19
Source : ReferenceNameBuilder.cs
with MIT License
from actions
with MIT License
from actions
internal void AppendSegment(String value)
{
if (String.IsNullOrEmpty(value))
{
return;
}
if (m_name.Length == 0)
{
var first = value[0];
if ((first >= 'a' && first <= 'z') ||
(first >= 'A' && first <= 'Z') ||
first == '_')
{
// Legal first char
}
else if ((first >= '0' && first <= '9') || first == '-')
{
// Illegal first char, but legal char.
// Prepend "_".
m_name.Append("_");
}
else
{
// Illegal char
}
}
else
{
// Separator
m_name.Append(c_separator);
}
foreach (var c in value)
{
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '_' ||
c == '-')
{
// Legal
m_name.Append(c);
}
else
{
// Illegal
m_name.Append("_");
}
}
}
19
Source : NameValidation.cs
with MIT License
from actions
with MIT License
from actions
public static String Sanitize(
String name,
Boolean allowHyphens = false)
{
if (name == null)
{
return String.Empty;
}
var sb = new StringBuilder();
for (Int32 i = 0; i < name.Length; i++)
{
if ((name[i] >= 'a' && name[i] <= 'z') ||
(name[i] >= 'A' && name[i] <= 'Z') ||
(name[i] >= '0' && name[i] <= '9' && sb.Length > 0) ||
(name[i] == '_') ||
(allowHyphens && name[i] == '-' && sb.Length > 0))
{
sb.Append(name[i]);
}
}
return sb.ToString();
}
19
Source : ArrayUtility.cs
with MIT License
from actions
with MIT License
from actions
public static String StringFromByteArray(byte[] bytes)
{
if (bytes == null || bytes.Length == 0)
{
return "null";
}
StringBuilder sb = new StringBuilder(bytes.Length * 2);
for (int i = 0; i < bytes.Length; i++)
{
byte b = bytes[i];
char first = (char)(((b >> 4) & 0x0F) + 0x30);
char second = (char)((b & 0x0F) + 0x30);
sb.Append(first >= 0x3A ? (char)(first + 0x27) : first);
sb.Append(second >= 0x3A ? (char)(second + 0x27) : second);
}
return sb.ToString();
}
19
Source : TemplateReader.cs
with MIT License
from actions
with MIT License
from actions
private static Boolean IsExpressionString(
String trimmed,
out String str)
{
var builder = new StringBuilder();
var inString = false;
for (var i = 0; i < trimmed.Length; i++)
{
var c = trimmed[i];
if (c == '\'')
{
inString = !inString;
if (inString && i != 0)
{
builder.Append(c);
}
}
else if (!inString)
{
str = default;
return false;
}
else
{
builder.Append(c);
}
}
str = builder.ToString();
return true;
}
19
Source : VssFileStorage.cs
with MIT License
from actions
with MIT License
from actions
public string PathKeyCombine(params string[] paths)
{
StringBuilder combinedPath = new StringBuilder();
foreach (string segment in paths)
{
if (segment != null)
{
string trimmedSegment = segment.TrimEnd(PathSeparator);
if (trimmedSegment.Length > 0)
{
if (combinedPath.Length > 0)
{
combinedPath.Append(PathSeparator);
}
combinedPath.Append(trimmedSegment);
}
}
}
return combinedPath.ToString();
}
19
Source : LexicalAnalyzer.cs
with MIT License
from actions
with MIT License
from actions
private Token ReadStringToken()
{
var startIndex = m_index;
var c = default(Char);
var closed = false;
var str = new StringBuilder();
m_index++; // Skip the leading single-quote.
while (m_index < m_expression.Length)
{
c = m_expression[m_index++];
if (c == '\'')
{
// End of string.
if (m_index >= m_expression.Length || m_expression[m_index] != '\'')
{
closed = true;
break;
}
// Escaped single quote.
m_index++;
}
str.Append(c);
}
var length = m_index - startIndex;
var rawValue = m_expression.Substring(startIndex, length);
if (closed)
{
return CreateToken(TokenKind.String, rawValue, startIndex, str.ToString());
}
return CreateToken(TokenKind.Unexpected, rawValue, startIndex);
}
19
Source : VssHttpUriUtility.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public static String ReplaceRouteValues(
String routeTemplate,
Dictionary<String, Object> routeValues,
RouteReplacementOptions routeReplacementOptions)
{
StringBuilder sbResult = new StringBuilder();
StringBuilder sbCurrentPathPart = new StringBuilder();
int paramStart = -1, paramLength = 0;
bool insideParam = false;
HashSet<string> unusedValues = new HashSet<string>(routeValues.Keys, StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> caseIncensitiveRouteValues = new Dictionary<string, object>(routeValues, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < routeTemplate.Length; i++)
{
char c = routeTemplate[i];
if (insideParam)
{
if (c == '}')
{
insideParam = false;
String paramName = routeTemplate.Substring(paramStart, paramLength);
paramLength = 0;
if (paramName.StartsWith("*"))
{
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.WildcardAsQueryParams))
{
continue;
}
// wildcard route
paramName = paramName.Substring(1);
}
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue))
{
if (paramValue != null)
{
sbCurrentPathPart.Append(paramValue.ToString());
unusedValues.Remove(paramName);
}
}
else if (routeReplacementOptions.HasFlag(RouteReplacementOptions.RequireExplicitRouteParams))
{
throw new ArgumentException("Missing route param " + paramName);
}
}
else
{
paramLength++;
}
}
else
{
if (c == '/')
{
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
sbCurrentPathPart.Clear();
}
}
else if (c == '{')
{
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '{')
{
// Escaped '{'
sbCurrentPathPart.Append(c);
i++;
}
else
{
insideParam = true;
paramStart = i + 1;
}
}
else if (c == '}')
{
sbCurrentPathPart.Append(c);
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '}')
{
// Escaped '}'
i++;
}
}
else
{
sbCurrentPathPart.Append(c);
}
}
}
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.EscapeUri))
{
sbResult = new StringBuilder(Uri.EscapeUriString(sbResult.ToString()));
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.AppendUnusedAsQueryParams) && unusedValues.Count > 0)
{
bool isFirst = true;
foreach (String paramName in unusedValues)
{
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue) && paramValue != null)
{
sbResult.Append(isFirst ? '?' : '&');
isFirst = false;
sbResult.Append(Uri.EscapeDataString(paramName));
sbResult.Append('=');
sbResult.Append(Uri.EscapeDataString(paramValue.ToString()));
}
}
}
return sbResult.ToString();
}
19
Source : VssHttpUriUtility.cs
with MIT License
from actions
with MIT License
from actions
public static Uri ConcatUri(Uri baseUri, String relativeUri)
{
StringBuilder sbCombined = new StringBuilder(baseUri.GetLeftPart(UriPartial.Path).TrimEnd('/'));
sbCombined.Append('/');
sbCombined.Append(relativeUri.TrimStart('/'));
sbCombined.Append(baseUri.Query);
return new Uri(sbCombined.ToString());
}
19
Source : VssApiResourceVersion.cs
with MIT License
from actions
with MIT License
from actions
public override string ToString()
{
StringBuilder sbVersion = new StringBuilder(ApiVersion.ToString(2));
if (IsPreview)
{
sbVersion.Append('-');
sbVersion.Append(c_PreviewStageName);
if (ResourceVersion > 0)
{
sbVersion.Append('.');
sbVersion.Append(ResourceVersion);
}
}
return sbVersion.ToString();
}
19
Source : CustomTreeListBoxItemAdapter.cs
with MIT License
from Actipro
with MIT License
from Actipro
private static string JoinItemFullPaths(TreeListBox toolboxControl, IEnumerable<object> items) {
var fullPaths = new StringBuilder();
foreach (var item in items)
fullPaths.Append(toolboxControl.GetFullPath(item)).Append('\n');
return fullPaths.ToString().TrimEnd();
}
19
Source : CustomSearchPatternProvider.cs
with MIT License
from Actipro
with MIT License
from Actipro
public string GetFindPattern(string pattern) {
// Convert _ characters to digits and leave * and + as their regex equivalent
string[] parts = pattern.Split(new char[] { '_', '*', '+' });
int index = 0;
StringBuilder result = new StringBuilder();
foreach (string part in parts) {
if (part.Length > 0)
result.Append(String.Format("\"{0}\"", RegexHelper.Escape(part)));
index += part.Length;
if (index < pattern.Length) {
if (pattern[index] == '_')
result.Append("[0-9]");
else
result.Append(pattern[index]);
}
index++;
}
return result.ToString();
}
19
Source : History.cs
with GNU Affero General Public License v3.0
from active-logic
with GNU Affero General Public License v3.0
from active-logic
static string TrimDetails(string self, char @in, char @out){
var x = new System.Text.StringBuilder();
var depth = 0;
for(int i = 0; i < self.Length; i++){
var c = self[i];
if(c == @in) depth++;
if(depth <= 0) x.Append(c);
if(c==@out) depth--;
} return x.ToString();
}
19
Source : DiagnosticVerifier.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private static string FormatDiagnostics(Diagnosticreplacedyzer replacedyzer, params Diagnostic[] diagnostics)
{
var builder = new StringBuilder();
for (int i = 0; i < diagnostics.Length; ++i)
{
builder.AppendLine("// " + diagnostics[i].ToString());
var replacedyzerType = replacedyzer.GetType();
var rules = replacedyzer.SupportedDiagnostics;
foreach (var rule in rules)
{
if (rule != null && rule.Id == diagnostics[i].Id)
{
var location = diagnostics[i].Location;
if (location == Location.None)
{
builder.AppendFormat("GetGlobalResult({0}.{1})", replacedyzerType.Name, rule.Id);
}
else
{
replacedert.True(location.IsInSource,
$"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");
string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;
builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
resultMethodName,
linePosition.Line + 1,
linePosition.Character + 1,
replacedyzerType.Name,
rule.Id);
}
if (i != diagnostics.Length - 1)
{
builder.Append(',');
}
builder.AppendLine();
break;
}
}
}
return builder.ToString();
}
19
Source : PublicClassXmlCommentFix.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private string GenerateDescriptionFromCamelCase(string name)
{
var descriptionStringBuilder = new StringBuilder();
for (int i = 0; i < name.Length; i++)
{
if (char.IsUpper(name[i]) && i > 0)
{
descriptionStringBuilder.Append(_descriptionWordsSeparator);
descriptionStringBuilder.Append(char.ToLower(name[i]));
}
else
{
descriptionStringBuilder.Append(name[i]);
}
}
return descriptionStringBuilder.ToString();
}
19
Source : ITypeSymbolExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static StringBuilder AppendClrStyleNestedTypeShortName(this StringBuilder builder, ITypeSymbol typeSymbol)
{
builder.Append(DefaultNestedTypesSeparator)
.Append(typeSymbol.Name);
if (!(typeSymbol is INamedTypeSymbol namedType) || !namedType.IsGenericType)
return builder;
var typeArgs = namedType.TypeArguments;
return builder.Append(DefaultGenericArgsCountSeparator)
.Append(typeArgs.Length);
}
19
Source : IndentUtils.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static string GetSyntaxNodeStringWithRemovedIndent(this SyntaxNode syntaxNode, int tabSize, int prependLength = 0)
{
if (tabSize <= 0)
{
throw new ArgumentException("Tab size must be positive", nameof(tabSize));
}
string syntaxNodeString = syntaxNode?.ToString();
if (syntaxNodeString.IsNullOrWhiteSpace())
return syntaxNodeString;
prependLength = tabSize * (prependLength / tabSize);
var indentLength = prependLength + syntaxNode.GetNodeIndentLength(tabSize);
if (indentLength == 0)
return syntaxNodeString;
var sb = new System.Text.StringBuilder(string.Empty, capacity: syntaxNodeString.Length);
int counter = 0;
bool isInsideString = false;
char prevChar = default;
foreach (char c in syntaxNodeString)
{
ProcessCurrentCharacter(c, prevChar);
prevChar = c;
}
return sb.ToString();
//-----------------------------------------------Local Function-------------------------------------
void ProcessCurrentCharacter(char c, char prevCharacter)
{
switch (c)
{
case '"':
ProcessQuotationCharacter(prevCharacter);
sb.Append(c);
return;
case '\n':
counter = 0;
sb.Append(c);
return;
case ' ' when counter < indentLength && !isInsideString: //-V3063
counter++;
return;
case '\t' when counter < indentLength && !isInsideString: //-V3063
counter += tabSize;
return;
case ' ' when counter >= indentLength || isInsideString:
case '\t' when counter >= indentLength || isInsideString:
default:
sb.Append(c);
return;
}
}
void ProcessQuotationCharacter(char prevCharacter)
{
switch (prevCharacter)
{
case '\\':
return;
default:
isInsideString = !isInsideString;
return;
}
}
}
19
Source : Lexer.cs
with MIT License
from adamant
with MIT License
from adamant
private static IEnumerable<IToken> Lex(CodeFile file, Diagnostics diagnostics)
{
var code = file.Code;
var text = code.Text;
var tokenStart = 0;
var tokenEnd = -1; // One past the end position to allow for zero length spans
while (tokenStart < text.Length)
{
var currentChar = text[tokenStart];
switch (currentChar)
{
case '{':
yield return TokenFactory.OpenBrace(SymbolSpan());
break;
case '}':
yield return TokenFactory.CloseBrace(SymbolSpan());
break;
case '(':
yield return TokenFactory.OpenParen(SymbolSpan());
break;
case ')':
yield return TokenFactory.CloseParen(SymbolSpan());
break;
case '[':
case ']':
case '|':
case '&':
case '@':
case '`':
case '$':
yield return NewReservedOperator();
break;
case ';':
yield return TokenFactory.Semicolon(SymbolSpan());
break;
case ',':
yield return TokenFactory.Comma(SymbolSpan());
break;
case '#':
switch (NextChar())
{
case '#':
// it is `##`
yield return NewReservedOperator(2);
break;
case '(':
// it is `#(`
yield return NewReservedOperator(2);
break;
case '[':
// it is `#[`
yield return NewReservedOperator(2);
break;
case '{':
// it is `#{`
yield return NewReservedOperator(2);
break;
default:
// it is `#`
yield return NewReservedOperator();
break;
}
break;
case '.':
if (NextChar() is '.')
{
if (CharAt(2) is '<')
// it is `..<`
yield return TokenFactory.DotDotLessThan(SymbolSpan(3));
else
// it is `..`
yield return TokenFactory.DotDot(SymbolSpan(2));
}
else
yield return TokenFactory.Dot(SymbolSpan());
break;
case ':':
if (NextChar() is ':' && CharAt(2) is '.')
// it is `::.`
yield return TokenFactory.ColonColonDot(SymbolSpan(3));
else
// it is `:`
yield return TokenFactory.Colon(SymbolSpan());
break;
case '?':
switch (NextChar())
{
case '?':
// it is `??`
yield return TokenFactory.QuestionQuestion(SymbolSpan(2));
break;
case '.':
// it is `?.`
yield return TokenFactory.QuestionDot(SymbolSpan(2));
break;
default:
// it is `?`
yield return TokenFactory.Question(SymbolSpan());
break;
}
break;
case '→':
yield return TokenFactory.RightArrow(SymbolSpan());
break;
case '⇒':
yield return TokenFactory.RightDoubleArrow(SymbolSpan());
break;
case '⬿':
yield return TokenFactory.LeftWaveArrow(SymbolSpan());
break;
case '⤳':
yield return TokenFactory.RightWaveArrow(SymbolSpan());
break;
case '^':
if (NextChar() is '.')
// it is `^.`
yield return NewReservedOperator(2);
else
// it is `^`
yield return NewReservedOperator();
break;
case '+':
if (NextChar() is '=')
// it is `+=`
yield return TokenFactory.PlusEquals(SymbolSpan(2));
else
// it is `+`
yield return TokenFactory.Plus(SymbolSpan());
break;
case '-':
switch (NextChar())
{
case '=':
// it is `-=`
yield return TokenFactory.MinusEquals(SymbolSpan(2));
break;
case '>':
// it is `->`
yield return TokenFactory.RightArrow(SymbolSpan(2));
break;
default:
// it is `-`
yield return TokenFactory.Minus(SymbolSpan());
break;
}
break;
case '~':
if (NextChar() is '>')
// it is `~>`
yield return TokenFactory.RightWaveArrow(SymbolSpan(2));
else
{
// it is `~` which isn't allowed
yield return NewUnexpectedCharacter();
}
break;
case '*':
if (NextChar() is '=')
// it is `*=`
yield return TokenFactory.AsteriskEquals(SymbolSpan(2));
else
// it is `*`
yield return TokenFactory.Asterisk(SymbolSpan());
break;
case '/':
switch (NextChar())
{
case '/':
// it is a line comment `//`
tokenEnd = tokenStart + 2;
// Include newline at end
while (tokenEnd < text.Length)
{
currentChar = text[tokenEnd];
tokenEnd += 1;
if (currentChar == '\r' || currentChar == '\n')
break;
}
yield return TokenFactory.Comment(TokenSpan());
break;
case '*':
// it is a block comment `/*`
tokenEnd = tokenStart + 2;
var lastCharWreplacedtar = false;
// Include slash at end
for (; ; )
{
// If we ran into the end of the file, error
if (tokenEnd >= text.Length)
{
diagnostics.Add(LexError.UnclosedBlockComment(file,
TextSpan.FromStartEnd(tokenStart, tokenEnd)));
break;
}
currentChar = text[tokenEnd];
tokenEnd += 1;
if (lastCharWreplacedtar && currentChar == '/')
break;
lastCharWreplacedtar = currentChar == '*';
}
yield return TokenFactory.Comment(TokenSpan());
break;
case '=':
// it is `/=`
yield return TokenFactory.SlashEquals(SymbolSpan(2));
break;
default:
// it is `/`
yield return TokenFactory.Slash(SymbolSpan());
break;
}
break;
case '=':
switch (NextChar())
{
case '>':
// it is `=>`
yield return TokenFactory.RightDoubleArrow(SymbolSpan(2));
break;
case '=':
// it is `==`
yield return TokenFactory.EqualsEquals(SymbolSpan(2));
break;
case '/':
if (CharAt(2) is '=')
// it is `=/=`
yield return TokenFactory.NotEqual(SymbolSpan(3));
else
goto default;
break;
default:
// it is `=`
yield return TokenFactory.Equals(SymbolSpan());
break;
}
break;
case '≠':
yield return TokenFactory.NotEqual(SymbolSpan());
break;
case '>':
if (NextChar() is '=')
// it is `>=`
yield return TokenFactory.GreaterThanOrEqual(SymbolSpan(2));
else
// it is `>`
yield return TokenFactory.GreaterThan(SymbolSpan());
break;
case '≥':
yield return TokenFactory.GreaterThanOrEqual(SymbolSpan());
break;
case '<':
switch (NextChar())
{
case '=':
// it is `<=`
yield return TokenFactory.LessThanOrEqual(SymbolSpan(2));
break;
case ':':
// it is `<:`
yield return TokenFactory.LessThanColon(SymbolSpan(2));
break;
case '~':
// it is `<~`
yield return TokenFactory.LeftWaveArrow(SymbolSpan(2));
break;
case '.':
if (CharAt(2) is '.')
{
if (CharAt(3) is '<')
// it is `<..<`
yield return TokenFactory.LessThanDotDotLessThan(SymbolSpan(4));
else
// it is `<..`
yield return TokenFactory.LessThanDotDot(SymbolSpan(3));
}
else
goto default;
break;
default:
// it is `<`
yield return TokenFactory.LessThan(SymbolSpan());
break;
}
break;
case '≤':
yield return TokenFactory.LessThanOrEqual(SymbolSpan());
break;
case '"':
yield return LexString();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
tokenEnd = tokenStart + 1;
while (tokenEnd < text.Length && IsIntegerCharacter(text[tokenEnd]))
tokenEnd += 1;
var span = TokenSpan();
var value = BigInteger.Parse(code[span], CultureInfo.InvariantCulture);
yield return TokenFactory.IntegerLiteral(span, value);
break;
}
case '\\':
{
tokenEnd = tokenStart + 1;
while (tokenEnd < text.Length && IsIdentifierCharacter(text[tokenEnd]))
tokenEnd += 1;
if (tokenEnd == tokenStart + 1)
yield return NewUnexpectedCharacter();
else
yield return NewEscapedIdentifier();
break;
}
default:
if (char.IsWhiteSpace(currentChar))
{
tokenEnd = tokenStart + 1;
// Include whitespace at end
while (tokenEnd < text.Length && char.IsWhiteSpace(text[tokenEnd]))
tokenEnd += 1;
yield return TokenFactory.Whitespace(TokenSpan());
}
else if (IsIdentifierStartCharacter(currentChar))
{
tokenEnd = tokenStart + 1;
while (tokenEnd < text.Length && IsIdentifierCharacter(text[tokenEnd]))
tokenEnd += 1;
yield return NewIdentifierOrKeywordToken();
}
else if (currentChar == '!' && NextChar() is '=')
{
var span = SymbolSpan(2);
diagnostics.Add(LexError.CStyleNotEquals(file, span));
yield return TokenFactory.NotEqual(span);
}
else
yield return NewUnexpectedCharacter();
break;
}
tokenStart = tokenEnd;
}
// The end of file token provides something to attach any final errors to
yield return TokenFactory.EndOfFile(SymbolSpan(0));
yield break;
TextSpan SymbolSpan(int length = 1)
{
var end = tokenStart + length;
return TokenSpan(end);
}
TextSpan TokenSpan(int? end = null)
{
tokenEnd = end ?? tokenEnd;
return TextSpan.FromStartEnd(tokenStart, tokenEnd);
}
IToken NewIdentifierOrKeywordToken()
{
var span = TokenSpan();
var value = code[span];
if (TokenTypes.KeywordFactories.TryGetValue(value, out var keywordFactory))
return keywordFactory(span);
if (value == "continue")
diagnostics.Add(LexError.ContinueInsteadOfNext(file, span));
else if (TokenTypes.ReservedWords.Contains(value)
|| TokenTypes.IsReservedTypeName(value))
diagnostics.Add(LexError.ReservedWord(file, span, value));
return TokenFactory.BareIdentifier(span, value);
}
IToken NewEscapedIdentifier()
{
var identifierStart = tokenStart + 1;
var span = TokenSpan();
var value = text[identifierStart..tokenEnd];
var isValidToEscape = TokenTypes.Keywords.Contains(value)
|| TokenTypes.ReservedWords.Contains(value)
|| TokenTypes.IsReservedTypeName(value)
|| char.IsDigit(value[0]);
if (!isValidToEscape)
diagnostics.Add(LexError.EscapedIdentifierShouldNotBeEscaped(file, span, value));
return TokenFactory.EscapedIdentifier(span, value);
}
IToken NewUnexpectedCharacter()
{
var span = SymbolSpan();
var value = code[span];
diagnostics.Add(LexError.UnexpectedCharacter(file, span, value[0]));
return TokenFactory.Unexpected(span);
}
IToken NewReservedOperator(int length = 1)
{
var span = SymbolSpan(length);
var value = code[span];
diagnostics.Add(LexError.ReservedOperator(file, span, value));
return TokenFactory.Unexpected(span);
}
char? NextChar()
{
var index = tokenStart + 1;
return index < text.Length ? text[index] : default;
}
char? CharAt(int offset)
{
var index = tokenStart + offset;
return index < text.Length ? text[index] : default;
}
IToken LexString()
{
tokenEnd = tokenStart + 1;
var content = new StringBuilder();
char currentChar;
while (tokenEnd < text.Length && (currentChar = text[tokenEnd]) != '"')
{
tokenEnd += 1;
if (currentChar != '\\')
{
content.Append(currentChar);
continue;
}
// Escape Sequence (i.e. "\\")
// In case of an invalid escape sequence, we just drop the `\` from the value
if (tokenEnd >= text.Length)
{
// Just the slash is invalid
var errorSpan = TextSpan.FromStartEnd(tokenEnd - 1, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
break; // we hit the end of file and need to not add to tokenEnd any more
}
// Escape Sequence with next char (i.e. "\\x")
var escapeStart = tokenEnd - 1;
currentChar = text[tokenEnd];
tokenEnd += 1;
switch (currentChar)
{
case '"':
case '\'':
case '\\':
content.Append(currentChar);
break;
case 'n':
content.Append('\n');
break;
case 'r':
content.Append('\r');
break;
case '0':
content.Append('\0');
break;
case 't':
content.Append('\t');
break;
case 'u':
{
if (tokenEnd < text.Length && text[tokenEnd] == '(')
tokenEnd += 1;
else
{
content.Append('u');
var errorSpan = TextSpan.FromStartEnd(escapeStart, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
break;
}
var codepoint = new StringBuilder(6);
while (tokenEnd < text.Length &&
IsHexDigit(currentChar = text[tokenEnd]))
{
codepoint.Append(currentChar);
tokenEnd += 1;
}
int value;
if (codepoint.Length > 0
&& codepoint.Length <= 6
&& (value = Convert.ToInt32(codepoint.ToString(), 16)) <= 0x10FFFF)
{
// TODO disallow surrogate pairs
content.Append(char.ConvertFromUtf32(value));
}
else
{
content.Append("u(");
content.Append(codepoint);
// Include the closing ')' in the escape sequence if it is present
if (tokenEnd < text.Length && text[tokenEnd] == ')')
{
content.Append(')');
tokenEnd += 1;
}
var errorSpan = TextSpan.FromStartEnd(escapeStart, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
break;
}
if (tokenEnd < text.Length && text[tokenEnd] == ')')
tokenEnd += 1;
else
{
var errorSpan = TextSpan.FromStartEnd(escapeStart, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
}
break;
}
default:
{
// Last two chars form the invalid sequence
var errorSpan = TextSpan.FromStartEnd(tokenEnd - 2, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
// drop the `/` keep the character after
content.Append(currentChar);
break;
}
}
}
if (tokenEnd < text.Length)
{
// To include the close quote
if (text[tokenEnd] == '"')
tokenEnd += 1;
}
else
diagnostics.Add(LexError.UnclosedStringLiteral(file,
TextSpan.FromStartEnd(tokenStart, tokenEnd)));
return TokenFactory.StringLiteral(TextSpan.FromStartEnd(tokenStart, tokenEnd), content.ToString());
}
}
19
Source : NameMangler.cs
with MIT License
from adamant
with MIT License
from adamant
private static void Mangle(TypeName typeName, StringBuilder builder)
{
switch (typeName)
{
default:
throw ExhaustiveMatch.Failed(typeName);
case Name name:
ManglePart(name.Text, builder);
break;
case SpecialTypeName specialName:
builder.Append('_');
ManglePart(specialName.Text, builder);
break;
}
}
19
Source : ObjectType.cs
with MIT License
from adamant
with MIT License
from adamant
public override string ToSourceCodeString()
{
var builder = new StringBuilder();
builder.Append(ReferenceCapability.ToSourceCodeString());
if (builder.Length > 0) builder.Append(' ');
builder.Append(ContainingNamespace);
if (ContainingNamespace != NamespaceName.Global) builder.Append('.');
builder.Append(Name);
return builder.ToString();
}
19
Source : ObjectType.cs
with MIT License
from adamant
with MIT License
from adamant
public override string ToILString()
{
var builder = new StringBuilder();
builder.Append(ReferenceCapability.ToILString());
builder.Append(' ');
builder.Append(ContainingNamespace);
if (ContainingNamespace != NamespaceName.Global) builder.Append('.');
builder.Append(Name);
return builder.ToString();
}
19
Source : MiniJson.cs
with MIT License
from AdamCarballo
with MIT License
from AdamCarballo
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
19
Source : MiniJson.cs
with MIT License
from AdamCarballo
with MIT License
from AdamCarballo
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
19
Source : MiniJson.cs
with MIT License
from AdamCarballo
with MIT License
from AdamCarballo
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
19
Source : MiniJson.cs
with MIT License
from AdamCarballo
with MIT License
from AdamCarballo
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
19
Source : StringExtensions.cs
with MIT License
from adamant
with MIT License
from adamant
public static string Escape(this string input)
{
var escaped = new StringBuilder(input.Length + 2);
foreach (var c in input)
{
switch (c)
{
case '\'':
escaped.Append(@"\'");
break;
case '\"':
escaped.Append("\\\"");
break;
case '\\':
escaped.Append(@"\\");
break;
case '\0':
escaped.Append(@"\0");
break;
case '\a':
escaped.Append(@"\a");
break;
case '\b':
escaped.Append(@"\b");
break;
case '\f':
escaped.Append(@"\f");
break;
case '\n':
escaped.Append(@"\n");
break;
case '\r':
escaped.Append(@"\r");
break;
case '\t':
escaped.Append(@"\t");
break;
case '\v':
escaped.Append(@"\v");
break;
default:
if (char.GetUnicodeCategory(c) != UnicodeCategory.Control)
escaped.Append(c);
else
{
escaped.Append(@"\u(");
escaped.Append(((ushort)c).ToString("x", CultureInfo.InvariantCulture));
escaped.Append(@")");
}
break;
}
}
return escaped.ToString();
}
19
Source : FileLogEntryTextBuilder.cs
with MIT License
from adams85
with MIT License
from adams85
protected virtual void AppendEventId(StringBuilder sb, EventId eventId)
{
sb.Append('[').Append(eventId).Append(']');
}
19
Source : FileLogEntryTextBuilder.cs
with MIT License
from adams85
with MIT License
from adams85
protected virtual void AppendLogScopeInfo(StringBuilder sb, IExternalScopeProvider scopeProvider)
{
var initialLength = sb.Length;
scopeProvider.ForEachScope((scope, state) =>
{
(StringBuilder builder, int length) = state;
var first = length == builder.Length;
if (!first)
builder.Append(' ');
AppendLogScope(builder, scope);
}, (sb, initialLength));
if (sb.Length > initialLength)
{
sb.Insert(initialLength, _messagePadding);
sb.AppendLine();
}
}
19
Source : POComment.cs
with MIT License
from adams85
with MIT License
from adams85
public override string ToString()
{
var idKindToken = POKey.GetIdKindToken(IdKind) ?? "?";
var value = Value ?? string.Empty;
var sb = new StringBuilder();
sb.Append(idKindToken);
sb.Append(' ');
sb.Append('"');
POString.Encode(sb, value, 0, value.Length);
sb.Append('"');
return sb.ToString();
}
19
Source : POGenerator.cs
with MIT License
from adams85
with MIT License
from adams85
private void AppendPOString(string value)
{
if (value == null)
value = string.Empty;
var startIndex = _builder.Length;
_builder.Append('"');
POString.Encode(_builder, value, 0, value.Length);
_builder.Append('"');
var endIndex = _builder.Length;
if (!(!HasFlags(Flags.IgnoreLongLines) && endIndex - _lineStartIndex > MaxLineLength ||
!HasFlags(Flags.IgnoreLineBreaks) && IndexOfNewLine(startIndex + 1, endIndex - 1) >= 0))
return;
startIndex++;
_builder.Insert(startIndex, _stringBreak);
_lineStartIndex = startIndex + _stringBreak.Length;
_lineStartIndex--;
while ((startIndex = GetStringBreakIndex()) >= 0)
{
_builder.Insert(startIndex, _stringBreak);
_lineStartIndex = startIndex + _stringBreak.Length;
_lineStartIndex--;
}
}
19
Source : POGenerator.cs
with MIT License
from adams85
with MIT License
from adams85
private void WriteEntryCommentsAndKey(IPOEntry entry)
{
if (!HasFlags(Flags.SkipComments) && entry.Comments != null)
WriteComments(entry.Comments);
if (entry.Key.ContextId != null)
{
ResetBuilder();
_builder.Append(POCatalog.ContextIdToken);
_builder.Append(' ');
AppendPOString(entry.Key.ContextId);
_writer.WriteLine(_builder);
}
ResetBuilder();
_builder.Append(POCatalog.IdToken);
_builder.Append(' ');
AppendPOString(entry.Key.Id);
_writer.WriteLine(_builder);
if (entry.Key.PluralId != null)
{
ResetBuilder();
_builder.Append(POCatalog.PluralIdToken);
_builder.Append(' ');
AppendPOString(entry.Key.PluralId);
_writer.WriteLine(_builder);
}
}
19
Source : POGenerator.cs
with MIT License
from adams85
with MIT License
from adams85
private void WritePluralEntryTranslation(int index, string translation)
{
ResetBuilder();
_builder.Append(POCatalog.TranslationToken);
_builder.Append('[');
_builder.Append(index, CultureInfo.InvariantCulture);
_builder.Append(']');
_builder.Append(' ');
AppendPOString(translation);
_writer.WriteLine(_builder);
}
19
Source : POString.cs
with MIT License
from adams85
with MIT License
from adams85
public static int Decode(StringBuilder builder, string source, int startIndex, int count, string newLine)
{
var endIndex = startIndex + count;
for (; startIndex < endIndex; startIndex++)
{
var c = source[startIndex];
if (c == '\\')
if (++startIndex < endIndex && TryDecodeEscapeSequence(builder, source[startIndex]))
continue;
else
return startIndex - 1;
builder.Append(c);
}
return -1;
bool TryDecodeEscapeSequence(StringBuilder b, char c)
{
switch (c)
{
case '\\': b.Append('\\'); return true;
case '"': b.Append('"'); return true;
case 't': b.Append('\t'); return true;
case 'n': b.Append(newLine); return true;
default: return false;
}
}
}
19
Source : POString.cs
with MIT License
from adams85
with MIT License
from adams85
public static void Encode(StringBuilder builder, string source, int startIndex, int count)
{
var endIndex = startIndex + count;
for (; startIndex < endIndex; startIndex++)
{
var c = source[startIndex];
switch (c)
{
case '\\': builder.Append('\\'); break;
case '"': builder.Append('\\'); break;
case '\t': builder.Append('\\'); c = 't'; break;
case '\r':
case '\n':
var index = startIndex;
if (c == '\r' && ++index < endIndex && source[index] == '\n')
startIndex = index;
builder.Append('\\'); c = 'n'; break;
}
builder.Append(c);
}
}
19
Source : POGenerator.cs
with MIT License
from adams85
with MIT License
from adams85
private void WriteSingularEntryTranslation(string translation)
{
ResetBuilder();
_builder.Append(POCatalog.TranslationToken);
_builder.Append(' ');
AppendPOString(translation);
_writer.WriteLine(_builder);
}
19
Source : CountDictionary.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public override string ToString()
{
//Order();
StringBuilder result = new StringBuilder();
result.AppendLine("{");
foreach (KeyValuePair<BigInteger, BigInteger> kvp in this)
{
result.Append('\t');
result.Append(kvp.Key.ToString().PadLeft(5));
result.Append(":\t");
result.AppendLine(kvp.Value.ToString().PadLeft(5));
}
result.Append("}");
return result.ToString();
}
19
Source : AdColonyUtils.cs
with Apache License 2.0
from AdColony
with Apache License 2.0
from AdColony
void SerializeString(string aString, StringBuilder builder)
{
builder.Append("\"");
char[] charArray = aString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char c = charArray[i];
if (c == '"')
{
builder.Append("\\\"");
}
else if (c == '\\')
{
builder.Append("\\\\");
}
else if (c == '\b')
{
builder.Append("\\b");
}
else if (c == '\f')
{
builder.Append("\\f");
}
else if (c == '\n')
{
builder.Append("\\n");
}
else if (c == '\r')
{
builder.Append("\\r");
}
else if (c == '\t')
{
builder.Append("\\t");
}
else
{
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126))
{
builder.Append(c);
}
else
{
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
}
}
builder.Append("\"");
}
19
Source : Utility.cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
public static string CreateRandomKey(int KeyLength)
{
const string valid = "012389ABCDEFGHIJKLMN4567OPQRSTUVWXYZ";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < KeyLength--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
19
Source : CustomLogEntryTextBuilder.cs
with MIT License
from adams85
with MIT License
from adams85
protected override void AppendLogLevel(StringBuilder sb, LogLevel logLevel)
{
sb.Append('[');
sb.Append(GetLogLevelString(logLevel));
sb.Append("]: ");
}
19
Source : VCalendar.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static void AppendField(StringBuilder vevent, string name, string value, bool encodeValue = true)
{
// If there's no value, don't append the field at all.
if (string.IsNullOrEmpty(value))
{
return;
}
// Get all the characters of the field (name + value), and break it into 72-character lines.
var fieldCharacters = (name + ":" + (encodeValue ? EncodeValue(value) : value)).ToCharArray();
for (var i = 0; i < fieldCharacters.Length; i++)
{
vevent.Append(fieldCharacters[i]);
// If we are at the end of the field, write a CRLF.
if (i == (fieldCharacters.Length - 1))
{
vevent.Append("\r\n");
}
// If we are at a 72 character boundary (but not the end), write a CRLF plus a space.
else if (i != 0 && i % 72 == 0)
{
vevent.Append("\r\n ");
}
}
}
See More Examples