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 : StringUtils.cs
with Apache License 2.0
from 0xFireball
with Apache License 2.0
from 0xFireball
public static string SecureRandomString(int maxSize)
{
var chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
var data = new byte[1];
using (var prng = RandomNumberGenerator.Create())
{
prng.GetBytes(data);
data = new byte[maxSize];
prng.GetBytes(data);
}
var result = new StringBuilder(maxSize);
foreach (var b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
19
Source : UriExtensions.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public static Uri AddQueryParameters(Uri uri, IEnumerable<KeyValuePair<string, string>> parameters)
{
var builder = new StringBuilder();
foreach (var param in parameters)
{
if (builder.Length > 0)
builder.Append('&');
builder.Append(Uri.EscapeDataString(param.Key));
builder.Append('=');
builder.Append(Uri.EscapeDataString(param.Value));
}
return AddQueryValue(uri, builder.ToString());
}
19
Source : ParamSfoEntry.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public static ParamSfoEntry Read(BinaryReader reader, ParamSfo paramSfo, int itemNumber)
{
const int indexOffset = 0x14;
const int indexEntryLength = 0x10;
reader.BaseStream.Seek(indexOffset + indexEntryLength * itemNumber, SeekOrigin.Begin);
var result = new ParamSfoEntry();
result.KeyOffset = reader.ReadUInt16();
result.ValueFormat = (EntryFormat)reader.ReadUInt16();
result.ValueLength = reader.ReadInt32();
result.ValueMaxLength = reader.ReadInt32();
result.ValueOffset = reader.ReadInt32();
reader.BaseStream.Seek(paramSfo.KeysOffset + result.KeyOffset, SeekOrigin.Begin);
byte tmp;
var sb = new StringBuilder(32);
while ((tmp = reader.ReadByte()) != 0)
sb.Append((char)tmp);
result.Key = sb.ToString();
reader.BaseStream.Seek(paramSfo.ValuesOffset + result.ValueOffset, SeekOrigin.Begin);
result.BinaryValue = reader.ReadBytes(result.ValueMaxLength);
return result;
}
19
Source : NamingStyles.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
private static string Delimitied(string value, char separator)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length == 0)
return value;
var hasPrefix = true;
var builder = new StringBuilder(value.Length + 3);
foreach (var c in value)
{
var ch = c;
if (char.IsUpper(ch))
{
ch = char.ToLower(ch);
if (!hasPrefix)
builder.Append(separator);
hasPrefix = true;
}
else
hasPrefix = false;
builder.Append(ch);
}
return builder.ToString();
}
19
Source : Program.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
internal static async Task Main(string[] args)
{
try
{
if (args.Length == 0)
{
Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
var isFirstChar = true;
var completedPath = false;
var path = new StringBuilder();
do
{
var keyInfo = Console.ReadKey(true);
if (isFirstChar)
{
isFirstChar = false;
if (keyInfo.KeyChar != '"')
return;
}
else
{
if (keyInfo.KeyChar == '"')
{
completedPath = true;
args = new[] {path.ToString()};
}
else
path.Append(keyInfo.KeyChar);
}
} while (!completedPath);
Console.Clear();
}
Console.OutputEncoding = new UTF8Encoding(false);
Console.replacedle = replacedle;
Console.CursorVisible = false;
Console.WriteLine("Scanning for PKGs...");
var pkgList = new List<FileInfo>();
Console.ForegroundColor = ConsoleColor.Yellow;
foreach (var item in args)
{
var path = item.Trim('"');
if (File.Exists(path))
pkgList.Add(new FileInfo(path));
else if (Directory.Exists(path))
pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
else
Console.WriteLine("Unknown path: " + path);
}
Console.ResetColor();
if (pkgList.Count == 0)
{
Console.WriteLine("No packages were found. Check paths, and try again.");
return;
}
var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
var sigWidth = Math.Max(HeaderSignature.Length, 8);
var csumWidth = Math.Max(HeaderChecksum.Length, 5);
var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
var idealWidth = longestFilename + csumsWidth;
try
{
if (idealWidth > Console.LargestWindowWidth)
{
longestFilename = Console.LargestWindowWidth - csumsWidth;
idealWidth = Console.LargestWindowWidth;
}
if (idealWidth > Console.WindowWidth)
{
Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
Console.WindowWidth = idealWidth;
}
Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
}
catch (PlatformNotSupportedException) { }
Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
var t = new Thread(() =>
{
try
{
var indicatorIdx = 0;
while (!cts.Token.IsCancellationRequested)
{
Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
if (cts.Token.IsCancellationRequested)
return;
PkgChecker.Sync.Wait(cts.Token);
try
{
var frame = Animation[(indicatorIdx++) % Animation.Length];
var currentProgress = PkgChecker.CurrentFileProcessedBytes;
Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
if (PkgChecker.CurrentPadding > 0)
{
Console.CursorVisible = false;
var (top, left) = (Console.CursorTop, Console.CursorLeft);
Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
Console.CursorTop = top;
Console.CursorLeft = left;
Console.CursorVisible = false;
}
}
finally
{
PkgChecker.Sync.Release();
}
}
}
catch (TaskCanceledException)
{
}
});
t.Start();
await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
cts.Cancel(false);
t.Join();
}
finally
{
Console.replacedle = replacedle;
Console.WriteLine("Press any key to exit");
Console.ReadKey();
Console.WriteLine();
Console.CursorVisible = true;
}
}
19
Source : DbQuery.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private string SqlEncoding(string sql)
{
var buffer = new StringBuilder();
for (int i = 0; i < sql.Length; i++)
{
var ch = sql[i];
if (ch == '\'' || ch == '-' || ch == '\\' || ch == '*' || ch == '@')
{
buffer.Append('\\');
}
buffer.Append(ch);
}
return buffer.ToString();
}
19
Source : StringHelper.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public string GenerateRandom(int length = 32)
{
var newRandom = new StringBuilder();
var rd = new Random();
for (int i = 0; i < length; i++)
{
newRandom.Append(_constant[rd.Next(_constant.Length)]);
}
return newRandom.ToString();
}
19
Source : StringHelper.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public string GenerateRandomNumber(int length = 6)
{
var newRandom = new StringBuilder();
var rd = new Random();
for (int i = 0; i < length; i++)
{
newRandom.Append(_constant[rd.Next(10)]);
}
return newRandom.ToString();
}
19
Source : DefaultCaptchaCodeGenerator.cs
with MIT License
from 1992w
with MIT License
from 1992w
public string Generate(int length)
{
Random rand = new Random();
int maxRand = Letters.Length - 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
int index = rand.Next(maxRand);
sb.Append(Letters[index]);
}
return sb.ToString();
}
19
Source : VBAGenerator.cs
with MIT License
from 1y0n
with MIT License
from 1y0n
public static string GetManifest(RuntimeVersion version)
{
StringBuilder builder = new StringBuilder();
string runtimeVersion = (version != RuntimeVersion.v2) ? "v4.0.30319" : "v2.0.50727";
string mscorlibVersion = (version != RuntimeVersion.v2) ? "4.0.0.0" : "2.0.0.0";
string template = Global_Var.manifest_template.Replace(
"%RUNTIMEVERSION%",
runtimeVersion
).Replace(
"%MSCORLIBVERSION%",
mscorlibVersion
);
for (int i = 0; i < template.Length; i++)
{
if (i == 0)
{
builder.Append("manifest = \"");
}
else if (i % 300 == 0)
{
builder.Append("\"");
builder.AppendLine();
builder.Append(" manifest = manifest & \"");
}
builder.Append(template[i]);
if (template[i] == '"') builder.Append('"');
}
builder.Append("\"");
return builder.ToString();
}
19
Source : VBAGenerator.cs
with MIT License
from 1y0n
with MIT License
from 1y0n
public string GenerateScript(byte[] serialized_object, string entry_clreplaced_name, string additional_script, RuntimeVersion version, bool enable_debug)
{
string hex_encoded = BitConverter.ToString(serialized_object).Replace("-", "");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hex_encoded.Length; i++)
{
if (i == 0)
{
builder.Append("s = \"");
}
else if (i % 300 == 0)
{
builder.Append("\"");
builder.AppendLine();
builder.Append(" s = s & \"");
}
builder.Append(hex_encoded[i]);
}
builder.Append("\"");
return GetScriptHeader(enable_debug) +
Global_Var.vba_template.Replace(
"%SERIALIZED%",
builder.ToString()
).Replace(
"%CLreplaced%",
entry_clreplaced_name
).Replace(
"%MANIFEST%",
GetManifest(version)
).Replace(
"%ADDEDSCRIPT%",
additional_script
);
}
19
Source : RedisWriter.cs
with MIT License
from 2881099
with MIT License
from 2881099
public byte[] Prepare(RedisCommand command)
{
var parts = command.Command.Split(' ');
int length = parts.Length + command.Arguments.Length;
StringBuilder sb = new StringBuilder();
sb.Append(MultiBulk).Append(length).Append(EOL);
foreach (var part in parts)
sb.Append(Bulk).Append(_io.Encoding.GetByteCount(part)).Append(EOL).Append(part).Append(EOL);
MemoryStream ms = new MemoryStream();
var data = _io.Encoding.GetBytes(sb.ToString());
ms.Write(data, 0, data.Length);
foreach (var arg in command.Arguments)
{
if (arg != null && arg.GetType() == typeof(byte[]))
{
data = arg as byte[];
var data2 = _io.Encoding.GetBytes($"{Bulk}{data.Length}{EOL}");
ms.Write(data2, 0, data2.Length);
ms.Write(data, 0, data.Length);
ms.Write(new byte[] { 13, 10 }, 0, 2);
}
else
{
string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg);
data = _io.Encoding.GetBytes($"{Bulk}{_io.Encoding.GetByteCount(str)}{EOL}{str}{EOL}");
ms.Write(data, 0, data.Length);
}
//string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg);
//sb.Append(Bulk).Append(_io.Encoding.GetByteCount(str)).Append(EOL).Append(str).Append(EOL);
}
return ms.ToArray();
}
19
Source : RedisReader.cs
with MIT License
from 2881099
with MIT License
from 2881099
string ReadLine()
{
StringBuilder sb = new StringBuilder();
char c;
bool should_break = false;
while (true)
{
c = (char)_io.ReadByte();
if (c == '\r') // TODO: remove hardcoded
should_break = true;
else if (c == '\n' && should_break)
break;
else
{
sb.Append(c);
should_break = false;
}
}
//Console.WriteLine($"ReadLine: {sb.ToString()}");
return sb.ToString();
}
19
Source : Calculator.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
public string Evaluate(string input, out bool success)
{
Success = true;
try
{
int depth = 0;
int start = 0;
StringBuilder output = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '(')
{
if (depth == 0)
start = i + 1;
depth++;
}
else if (input[i] == ')')
{
depth--;
if (depth == 0)
{
if (i - start > 0)
output.Append(ExpressionEvaluator(input.Substring(start, i - start)));
}
else if (depth == -1)
{
Success = false;
depth = 0;
}
}
else if (depth == 0)
output.Append(input[i]);
}
if (depth != 0)
Success = false;
success = Success;
return output.ToString();
}
catch
{
success = false;
return "ERROR";
}
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State1 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r')
continue;
if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '"':
ctx.NextState = 19;
ctx.Return = true;
return true;
case ',':
case ':':
case '[':
case ']':
case '{':
case '}':
ctx.NextState = 1;
ctx.Return = true;
return true;
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 2;
return true;
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
case 'f':
ctx.NextState = 12;
return true;
case 'n':
ctx.NextState = 16;
return true;
case 't':
ctx.NextState = 9;
return true;
case '\'':
if (! ctx.L.allow_single_quoted_strings)
return false;
ctx.L.input_char = '"';
ctx.NextState = 23;
ctx.Return = true;
return true;
case '/':
if (! ctx.L.allow_comments)
return false;
ctx.NextState = 25;
return true;
default:
return false;
}
}
return true;
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State2 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
default:
return false;
}
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State3 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State4 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State7 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
}
switch (ctx.L.input_char) {
case '+':
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
default:
return false;
}
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State19 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '"':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 20;
return true;
case '\\':
ctx.StateStack = 19;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State21 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 22;
return true;
case '"':
case '\'':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
ctx.L.string_buffer.Append (
ProcessEscChar (ctx.L.input_char));
ctx.NextState = ctx.StateStack;
return true;
default:
return false;
}
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State22 (FsmContext ctx)
{
int counter = 0;
int mult = 4096;
ctx.L.unichar = 0;
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' ||
ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' ||
ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') {
ctx.L.unichar += HexValue (ctx.L.input_char) * mult;
counter++;
mult /= 16;
if (counter == 4) {
ctx.L.string_buffer.Append (
Convert.ToChar (ctx.L.unichar));
ctx.NextState = ctx.StateStack;
return true;
}
continue;
}
return false;
}
return true;
}
19
Source : PersonFuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public string GeneratePreplacedword(int? minSize = null, int? maxSize = null, bool? includeSpecialCharacters = null)
{
var defaultMinSize = 7;
var defaultMaxSize = 12;
var minimumSize = minSize ?? defaultMinSize;
var maximumSize = maxSize ?? defaultMaxSize;
CheckGuardMinAndMaximumSizes(minSize, maxSize, minimumSize, maximumSize, defaultMinSize, defaultMaxSize);
var preplacedwordSize = _fuzzer.Random.Next(minimumSize, maximumSize + 1);
var pwd = new StringBuilder(preplacedwordSize);
for (var i = 0; i < preplacedwordSize; i++)
{
if ((i == 0 || i == 10) && (includeSpecialCharacters.HasValue && includeSpecialCharacters.Value))
{
pwd.Append(_specialCharacters[_fuzzer.Random.Next(0, _specialCharacters.Length)]);
continue;
}
if (i == 4 || i == 14)
{
pwd.Append(_upperCharacters[_fuzzer.Random.Next(1, 26)]);
continue;
}
if (i == 6 || i == 13)
{
pwd.Append(_numericCharacters[_fuzzer.Random.Next(4, 10)]);
continue;
}
if (i == 3 || i == 9)
{
pwd.Append(_numericCharacters[_fuzzer.Random.Next(1, 5)]);
continue;
}
// by default
pwd.Append(_lowerCharacters[_fuzzer.Random.Next(1, 26)]);
}
return pwd.ToString();
}
19
Source : StringFuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public string GenerateStringFromPattern(string diverseFormat)
{
var builder = new StringBuilder(diverseFormat.Length);
foreach (var c in diverseFormat.ToCharArray())
{
switch (c)
{
case '#':
builder.Append(_fuzzer.GenerateInteger(0,9));
break;
case 'X': builder.Append(_fuzzer.GenerateLetter().ToString().ToUpper());
break;
case 'x': builder.Append(_fuzzer.GenerateLetter());
break;
default: builder.Append(c);
break;
}
}
return builder.ToString();
}
19
Source : StringExtensions.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static string RemoveDiacritics(this string text)
{
// from https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static string NumToHexString(long qq, int length = 8)
{
var text = Convert.ToString(qq, 16);
if (text.Length == length)
{
return text;
}
if (text.Length > length)
{
return null;
}
var num = length - text.Length;
var str = "";
for (var i = 0; i < num; i++)
{
str += "0";
}
text = (str + text).ToUpper();
var stringBuilder = new StringBuilder();
for (var j = 0; j < text.Length; j++)
{
stringBuilder.Append(text[j]);
if ((j + 1) % 2 == 0)
{
stringBuilder.Append(" ");
}
}
return stringBuilder.ToString();
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State5 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 6;
return true;
}
return false;
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State6 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State8 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
return true;
}
19
Source : Lexer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool State23 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '\'':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 24;
return true;
case '\\':
ctx.StateStack = 23;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
19
Source : JSONParser.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
public static T FromJson<T>(this string json) {
//Remove all whitespace not within strings to make parsing simpler
stringBuilder.Length = 0;
for (int i = 0; i < json.Length; i++) {
char c = json[i];
if (c == '\"') {
i = AppendUntilStringEnd(true, i, json);
continue;
}
if (char.IsWhiteSpace(c))
continue;
stringBuilder.Append(c);
}
//Parse the thing!
return (T)ParseValue(typeof(T), stringBuilder.ToString());
}
19
Source : JSONParser.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
static int AppendUntilStringEnd(bool appendEscapeCharacter, int startIdx, string json) {
stringBuilder.Append(json[startIdx]);
for (int i = startIdx + 1; i < json.Length; i++) {
if (json[i] == '\\') {
if (appendEscapeCharacter)
stringBuilder.Append(json[i]);
stringBuilder.Append(json[i + 1]);
i++;//Skip next character as it is escaped
} else if (json[i] == '\"') {
stringBuilder.Append(json[i]);
return i;
} else
stringBuilder.Append(json[i]);
}
return json.Length - 1;
}
19
Source : SimpleJSON.cs
with MIT License
from 71
with MIT License
from 71
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONObject());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token.Length > 0 || TokenIsQuoted)
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
TokenIsQuoted = false;
TokenName = "";
Token.Length = 0;
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
break;
case '"':
QuoteMode ^= true;
TokenIsQuoted |= QuoteMode;
break;
case ',':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (Token.Length > 0 || TokenIsQuoted)
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
TokenIsQuoted = false;
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token.Append(aJSON[i]);
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't':
Token.Append('\t');
break;
case 'r':
Token.Append('\r');
break;
case 'n':
Token.Append('\n');
break;
case 'b':
Token.Append('\b');
break;
case 'f':
Token.Append('\f');
break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
i += 4;
break;
}
default:
Token.Append(C);
break;
}
}
break;
default:
Token.Append(aJSON[i]);
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
if (ctx == null)
return ParseElement(Token.ToString(), TokenIsQuoted);
return ctx;
}
19
Source : SimpleJSON.cs
with MIT License
from 71
with MIT License
from 71
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('[');
int count = m_List.Count;
if (inline)
aMode = JSONTextMode.Compact;
for (int i = 0; i < count; i++)
{
if (i > 0)
aSB.Append(',');
if (aMode == JSONTextMode.Indent)
aSB.AppendLine();
if (aMode == JSONTextMode.Indent)
aSB.Append(' ', aIndent + aIndentInc);
m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
}
if (aMode == JSONTextMode.Indent)
aSB.AppendLine().Append(' ', aIndent);
aSB.Append(']');
}
19
Source : SimpleJSON.cs
with MIT License
from 71
with MIT License
from 71
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('{');
bool first = true;
if (inline)
aMode = JSONTextMode.Compact;
foreach (var k in m_Dict)
{
if (!first)
aSB.Append(',');
first = false;
if (aMode == JSONTextMode.Indent)
aSB.AppendLine();
if (aMode == JSONTextMode.Indent)
aSB.Append(' ', aIndent + aIndentInc);
aSB.Append('\"').Append(Escape(k.Key)).Append('\"');
if (aMode == JSONTextMode.Compact)
aSB.Append(':');
else
aSB.Append(" : ");
k.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
}
if (aMode == JSONTextMode.Indent)
aSB.AppendLine().Append(' ', aIndent);
aSB.Append('}');
}
19
Source : JSONParser.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
static List<string> Split(string json) {
List<string> splitArray = splitArrayPool.Count > 0 ? splitArrayPool.Pop() : new List<string>();
splitArray.Clear();
int parseDepth = 0;
stringBuilder.Length = 0;
for (int i = 1; i < json.Length - 1; i++) {
switch (json[i]) {
case '[':
case '{':
parseDepth++;
break;
case ']':
case '}':
parseDepth--;
break;
case '\"':
i = AppendUntilStringEnd(true, i, json);
continue;
case ',':
case ':':
if (parseDepth == 0) {
splitArray.Add(stringBuilder.ToString());
stringBuilder.Length = 0;
continue;
}
break;
}
stringBuilder.Append(json[i]);
}
splitArray.Add(stringBuilder.ToString());
return splitArray;
}
19
Source : SimpleJSON.cs
with MIT License
from 71
with MIT License
from 71
internal static string Escape(string aText)
{
var sb = EscapeBuilder;
sb.Length = 0;
if (sb.Capacity < aText.Length + aText.Length / 10)
sb.Capacity = aText.Length + aText.Length / 10;
foreach (char c in aText)
{
switch (c)
{
case '\\':
sb.Append("\\\\");
break;
case '\"':
sb.Append("\\\"");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
default:
if (c < ' ' || (forceASCII && c > 127))
{
ushort val = c;
sb.Append("\\u").Append(val.ToString("X4"));
}
else
sb.Append(c);
break;
}
}
string result = sb.ToString();
sb.Length = 0;
return result;
}
19
Source : SimpleJSON.cs
with MIT License
from 71
with MIT License
from 71
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('\"').Append(Escape(m_Data)).Append('\"');
}
19
Source : Visitor.Expressions.cs
with MIT License
from 71
with MIT License
from 71
public override Expression VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node)
{
StringBuilder template = new StringBuilder();
Sequence<Expression> parameters = new Sequence<Expression>();
foreach (var content in node.Contents)
{
if (content is InterpolatedStringTextSyntax text)
{
template.Append(text.TextToken.ValueText);
}
else if (content is InterpolationSyntax interpolation)
{
template.Append('{');
template.Append(parameters.Count);
template.Append('}');
parameters.Add(interpolation.Expression.Accept(this));
}
else
{
throw new NotSupportedException();
}
}
return Expression.Call(
typeof(string).GetRuntimeMethod(nameof(string.Format), new[] { typeof(string), typeof(object[]) }),
Expression.Constant(template.ToString()),
Expression.NewArrayInit(typeof(object), parameters.ToArray())
);
}
19
Source : StringExtension.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public static string GenerateRandom(this String obj, int Length)
{
StringBuilder newRandom = new StringBuilder(constant.Length);
Random rd = new Random();
for (int i = 0; i < Length; i++)
{
newRandom.Append(constant[rd.Next(constant.Length)]);
}
return newRandom.ToString();
}
19
Source : StringMethods.cs
with MIT License
from 8T4
with MIT License
from 8T4
private static string RemoveAccent(this string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
19
Source : UserCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
private string GenerateRandom(int Length)
{
char[] constant =
{
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
};
StringBuilder newRandom = new StringBuilder(constant.Length);
Random rd = new Random();
for (int i = 0; i < Length; i++)
{
newRandom.Append(constant[rd.Next(constant.Length)]);
}
return newRandom.ToString().ToUpper();
}
19
Source : ExtensionMethods.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public static string BreakupCamelCase(this String str)
{
StringBuilder sb = new StringBuilder();
for (int i=0;i<str.Length;i++)
{
char c = str[i];
if (i > 0 && char.IsUpper(c))
{
sb.Append(' ');
}
if (i==0)
c = char.ToUpper(c);
sb.Append(c);
}
return sb.ToString();
}
19
Source : Common.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public static string Random(int length = 8)
{
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var randomString = new StringBuilder();
var random = new Random();
for (int i = 0; i < length; i++)
randomString.Append(chars[random.Next(chars.Length)]);
return randomString.ToString();
}
19
Source : CsharpMemberProvider.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public IEnumerable<string> GetConstructorParameters(string constructorString)
{
var index = 0;
var openedBracket = 0;
while (constructorString[index] != '(')
index++;
var sb = new StringBuilder();
while (constructorString[index] != ')')
{
index++;
if (constructorString[index] == '<')
openedBracket++;
else if (constructorString[index] == '>')
openedBracket--;
if (openedBracket ==0 && (constructorString[index] == ',' || constructorString[index] == ')'))
{
yield return sb.ToString();
sb.Clear();
}
else
sb.Append(constructorString[index]);
}
}
19
Source : RuntimeWeaponGenerator.cs
with MIT License
from Abdelfattah-Radwan
with MIT License
from Abdelfattah-Radwan
public static string GenerateRandomWeaponName(string format)
{
if (string.IsNullOrEmpty(format) || string.IsNullOrWhiteSpace(format))
{
return "Unnamed";
}
else
{
StringBuilder nameStringBuilder = new StringBuilder();
for (int i = 0; i < format.Length; i++)
{
char currentCharacter = format[i];
if (currentCharacter == 'D')
{
nameStringBuilder.Append(Digits[Random.Range(0, Digits.Length)]);
}
else if (currentCharacter == 'L')
{
nameStringBuilder.Append(Letters[Random.Range(0, Letters.Length)]);
}
else
{
nameStringBuilder.Append(currentCharacter);
}
}
return nameStringBuilder.ToString();
}
}
19
Source : V1Loader.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
static string ImportRegex(string expr, bool singleWord, bool? startOfLine)
{
StringBuilder b = new StringBuilder();
if (startOfLine != null) {
if (startOfLine.Value) {
b.Append(@"(?<=(^\s*))");
} else {
b.Append(@"(?<!(^\s*))");
}
} else {
if (singleWord)
b.Append(@"\b");
}
for (int i = 0; i < expr.Length; i++) {
char c = expr[i];
if (c == '@') {
++i;
if (i == expr.Length)
throw new HighlightingDefinitionInvalidException("Unexpected end of @ sequence, use @@ to look for a single @.");
switch (expr[i]) {
case 'C': // match whitespace or punctuation
b.Append(@"[^\w\d_]");
break;
case '!': // negative lookahead
{
StringBuilder whatmatch = new StringBuilder();
++i;
while (i < expr.Length && expr[i] != '@') {
whatmatch.Append(expr[i++]);
}
b.Append("(?!(");
b.Append(Regex.Escape(whatmatch.ToString()));
b.Append("))");
}
break;
case '-': // negative lookbehind
{
StringBuilder whatmatch = new StringBuilder();
++i;
while (i < expr.Length && expr[i] != '@') {
whatmatch.Append(expr[i++]);
}
b.Append("(?<!(");
b.Append(Regex.Escape(whatmatch.ToString()));
b.Append("))");
}
break;
case '@':
b.Append("@");
break;
default:
throw new HighlightingDefinitionInvalidException("Unknown character in @ sequence.");
}
} else {
b.Append(Regex.Escape(c.ToString()));
}
}
if (singleWord)
b.Append(@"\b");
return b.ToString();
}
19
Source : XmlHighlightingDefinition.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public object VisitKeywords(XshdKeywords keywords)
{
if (keywords.Words.Count == 0)
return Error(keywords, "Keyword group must not be empty.");
foreach (string keyword in keywords.Words) {
if (string.IsNullOrEmpty(keyword))
throw Error(keywords, "Cannot use empty string as keyword");
}
StringBuilder keyWordRegex = new StringBuilder();
// We can use "\b" only where the keyword starts/ends with a letter or digit, otherwise we don't
// highlight correctly. (example: ILAsm-Mode.xshd with ".maxstack" keyword)
if (keywords.Words.All(IsSimpleWord)) {
keyWordRegex.Append(@"\b(?>");
// (?> = atomic group
// atomic groups increase matching performance, but we
// must ensure that the keywords are sorted correctly.
// "\b(?>in|int)\b" does not match "int" because the atomic group captures "in".
// To solve this, we are sorting the keywords by descending length.
int i = 0;
foreach (string keyword in keywords.Words.OrderByDescending(w => w.Length)) {
if (i++ > 0)
keyWordRegex.Append('|');
keyWordRegex.Append(Regex.Escape(keyword));
}
keyWordRegex.Append(@")\b");
} else {
keyWordRegex.Append('(');
int i = 0;
foreach (string keyword in keywords.Words) {
if (i++ > 0)
keyWordRegex.Append('|');
if (char.IsLetterOrDigit(keyword[0]))
keyWordRegex.Append(@"\b");
keyWordRegex.Append(Regex.Escape(keyword));
if (char.IsLetterOrDigit(keyword[keyword.Length - 1]))
keyWordRegex.Append(@"\b");
}
keyWordRegex.Append(')');
}
return new HighlightingRule {
Color = GetColor(keywords, keywords.ColorReference),
Regex = CreateRegex(keywords, keyWordRegex.ToString(), XshdRegexType.Default)
};
}
19
Source : IndentationReformatter.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
{
string line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
StringBuilder indent = new StringBuilder();
if (line.Length == 0) {
// Special treatment for empty lines:
if (blockComment || (inString && verbatim))
return;
indent.Append(block.InnerIndent);
indent.Append(Repeat(set.IndentString, block.OneLineBlock));
if (block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
Block oldBlock = block;
bool startInComment = blockComment;
bool startInString = (inString && verbatim);
#region Parse char by char
lineComment = false;
inChar = false;
escape = false;
if (!verbatim) inString = false;
lastRealChar = '\n';
char lastchar = ' ';
char c = ' ';
char nextchar = line[0];
for (int i = 0; i < line.Length; i++) {
if (lineComment) break; // cancel parsing current line
lastchar = c;
c = nextchar;
if (i + 1 < line.Length)
nextchar = line[i + 1];
else
nextchar = '\n';
if (escape) {
escape = false;
continue;
}
#region Check for comment/string chars
switch (c) {
case '/':
if (blockComment && lastchar == '*')
blockComment = false;
if (!inString && !inChar) {
if (!blockComment && nextchar == '/')
lineComment = true;
if (!lineComment && nextchar == '*')
blockComment = true;
}
break;
case '#':
if (!(inChar || blockComment || inString))
lineComment = true;
break;
case '"':
if (!(inChar || lineComment || blockComment)) {
inString = !inString;
if (!inString && verbatim) {
if (nextchar == '"') {
escape = true; // skip escaped quote
inString = true;
} else {
verbatim = false;
}
} else if (inString && lastchar == '@') {
verbatim = true;
}
}
break;
case '\'':
if (!(inString || lineComment || blockComment)) {
inChar = !inChar;
}
break;
case '\\':
if ((inString && !verbatim) || inChar)
escape = true; // skip next character
break;
}
#endregion
if (lineComment || blockComment || inString || inChar) {
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
continue;
}
if (!Char.IsWhiteSpace(c) && c != '[' && c != '/') {
if (block.Bracket == '{')
block.Continuation = true;
}
if (Char.IsLetterOrDigit(c)) {
wordBuilder.Append(c);
} else {
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c) {
case '{':
block.ResetOneLineBlock();
blocks.Push(block);
block.StartLine = doc.LineNumber;
if (block.LastWord == "switch") {
block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
} else {
block.Indent(set);
}
block.Bracket = '{';
break;
case '}':
while (block.Bracket != '{') {
if (blocks.Count == 0) break;
block = blocks.Pop();
}
if (blocks.Count == 0) break;
block = blocks.Pop();
block.Continuation = false;
block.ResetOneLineBlock();
break;
case '(':
case '[':
blocks.Push(block);
if (block.StartLine == doc.LineNumber)
block.InnerIndent = block.OuterIndent;
else
block.StartLine = doc.LineNumber;
block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new String(' ', i + 1)));
block.Bracket = c;
break;
case ')':
if (blocks.Count == 0) break;
if (block.Bracket == '(') {
block = blocks.Pop();
if (IsSingleStatementKeyword(block.LastWord))
block.Continuation = false;
}
break;
case ']':
if (blocks.Count == 0) break;
if (block.Bracket == '[')
block = blocks.Pop();
break;
case ';':
case ',':
block.Continuation = false;
block.ResetOneLineBlock();
break;
case ':':
if (block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(block.LastWord + ":", StringComparison.Ordinal)) {
block.Continuation = false;
block.ResetOneLineBlock();
}
break;
}
if (!Char.IsWhiteSpace(c)) {
// register this char as last char
lastRealChar = c;
}
#endregion
}
#endregion
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}') {
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
} else {
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') {
indent.Remove(indent.Length - 1, 1);
} else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') {
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':') {
oldBlock.Continuation = true;
} else if (lastRealChar == ':' && indent.Length >= set.IndentString.Length) {
if (block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
} else if (lastRealChar == ')') {
if (IsSingleStatementKeyword(block.LastWord)) {
block.OneLineBlock++;
}
} else if (lastRealChar == 'e' && block.LastWord == "else") {
block.OneLineBlock = Math.Max(1, block.PreviousOneLineBlock);
block.Continuation = false;
oldBlock.OneLineBlock = block.OneLineBlock - 1;
}
if (doc.IsReadOnly) {
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == block.StartLine &&
block.StartLine < doc.LineNumber && lastRealChar != ':') {
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
for (int i = 0; i < line.Length; ++i) {
if (!Char.IsWhiteSpace(line[i]))
break;
indent.Append(line[i]);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') {
indent.Length -= 1;
}
block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{') {
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
Char.IsWhiteSpace(doc.Text[indent.Length])) {
doc.Text = indent.ToString() + line;
}
}
19
Source : ImmutableStack.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public override string ToString()
{
StringBuilder b = new StringBuilder("[Stack");
foreach (T val in this) {
b.Append(' ');
b.Append(val);
}
b.Append(']');
return b.ToString();
}
See More Examples