Here are the examples of the csharp api System.Collections.Generic.Dictionary.ContainsKey(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
208 Examples
19
Source : _242_ValidAnagram.cs
with MIT License
from AlexChesser
with MIT License
from AlexChesser
public bool IsAnagram(string s, string t)
{
if (s.Length != t.Length)
{
return false;
}
Dictionary<char, int> chars = new Dictionary<char, int>();
foreach (char c in s.ToCharArray())
{
if (!chars.ContainsKey(c))
{
chars.Add(c, 1);
}
else
{
chars[c]++;
}
}
foreach (char c in t.ToCharArray())
{
if (!chars.ContainsKey(c))
{
return false;
}
if (--chars[c] <= 0)
{
chars.Remove(c);
}
}
return true;
}
19
Source : _383_RansomNote.cs
with MIT License
from AlexChesser
with MIT License
from AlexChesser
public bool CanConstruct(string ransomNote, string magazine)
{
if (magazine.Length < ransomNote.Length)
{
return false;
}
Dictionary<char, int> lettersCount = new();
char[] mag = magazine.ToCharArray();
foreach (char c in mag)
{
if (!lettersCount.ContainsKey(c))
{
lettersCount.Add(c, 1);
}
else
{
lettersCount[c]++;
}
}
foreach (char c in ransomNote)
{
if (!lettersCount.ContainsKey(c))
{
return false;
}
if (--lettersCount[c] == 0)
{
lettersCount.Remove(c);
}
}
return true;
}
19
Source : _387_FirstUniqueCharacterinaString.cs
with MIT License
from AlexChesser
with MIT License
from AlexChesser
public int FirstUniqChar(string s)
{
Dictionary<char, int> count = new Dictionary<char, int>();
char[] arr = s.ToCharArray();
for (int i = 0; i < arr.Length; i++)
{
if (!count.ContainsKey(arr[i]))
{
// store position and count
count.Add(arr[i], 1);
}
else
{
count[arr[i]]++;
}
}
for (int i = 0; i < arr.Length; i++)
{
if (count[arr[i]] == 1) return i;
}
return -1;
}
19
Source : DHLProvider.cs
with MIT License
from alexeybusygin
with MIT License
from alexeybusygin
private void ParseRates(IEnumerable<XElement> rates)
{
var includedServices = _configuration.ServicesIncluded;
var excludedServices = _configuration.ServicesExcluded;
foreach (var rateNode in rates)
{
var serviceCode = rateNode.Element("GlobalProductCode")?.Value;
if (string.IsNullOrEmpty(serviceCode) || !AvailableServices.ContainsKey(serviceCode[0]))
{
AddInternalError($"Unknown DHL Global Product Code: {serviceCode}");
continue;
}
if ((includedServices.Any() && !includedServices.Contains(serviceCode[0])) ||
(excludedServices.Any() && excludedServices.Contains(serviceCode[0])))
{
continue;
}
var name = rateNode.Element("ProductShortName")?.Value;
var description = AvailableServices[serviceCode[0]];
var totalCharges = Convert.ToDecimal(rateNode.Element("ShippingCharge")?.Value, CultureInfo.InvariantCulture);
var currencyCode = rateNode.Element("CurrencyCode")?.Value;
var deliveryDateValue = rateNode.XPathSelectElement("DeliveryDate")?.Value;
var deliveryTimeValue = rateNode.XPathSelectElement("DeliveryTime")?.Value;
if (!DateTime.TryParse(deliveryDateValue, out DateTime deliveryDate))
deliveryDate = DateTime.MaxValue;
if (!string.IsNullOrEmpty(deliveryTimeValue) && deliveryTimeValue.Length >= 4)
{
// Parse PTxxH or PTxxHyyM to time
var indexOfH = deliveryTimeValue.IndexOf('H');
if (indexOfH >= 3)
{
var hours = int.Parse(deliveryTimeValue.Substring(2, indexOfH - 2), CultureInfo.InvariantCulture);
var minutes = 0;
var indexOfM = deliveryTimeValue.IndexOf('M');
if (indexOfM > indexOfH)
{
minutes = int.Parse(deliveryTimeValue.Substring(indexOfH + 1, indexOfM - indexOfH - 1), CultureInfo.InvariantCulture);
}
deliveryDate = deliveryDate.Date + new TimeSpan(hours, minutes, 0);
}
}
AddRate(name, description, totalCharges, deliveryDate, new RateOptions()
{
SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
},
currencyCode);
}
}
19
Source : Program.cs
with MIT License
from AnkitSharma-007
with MIT License
from AnkitSharma-007
internal static void Countcharacter(string str)
{
/* input:- hello world ;
* output:- h - 1
e - 1
l - 3
o - 2
w - 1
r - 1
d - 1
*
* */
Dictionary<char, int> characterCount = new Dictionary<char, int>();
foreach (var character in str)
{
if (character != ' ')
{
if (!characterCount.ContainsKey(character))
{
characterCount.Add(character, 1);
}
else
{
characterCount[character]++;
}
}
}
foreach (var character in characterCount)
{
Console.WriteLine("{0} - {1}", character.Key, character.Value);
}
}
19
Source : LetterGlyphTool.cs
with Apache License 2.0
from anmcgrath
with Apache License 2.0
from anmcgrath
public GrayScaleLetterGlyph GetGrayScaleLetter(char ch)
{
lock (Glyphs)
{
if (!Glyphs.ContainsKey(ch))
{
Glyphs[ch] = GrayScaleLetterGlyph.CreateGlyph(Typeface, GlyphTypeface, EmSize, ch);
}
return Glyphs[ch];
}
}
19
Source : GlyphLegality.cs
with MIT License
from architdate
with MIT License
from architdate
public static bool ContainsHalfWidth(string val) => val.Any(z => CharDictionary.ContainsKey(z));
19
Source : GlyphLegality.cs
with MIT License
from architdate
with MIT License
from architdate
public static string StringConvert(string val, StringConversionType type)
{
return type switch
{
StringConversionType.HalfWidth => val.Normalize(NormalizationForm.FormKC),
StringConversionType.FullWidth => string.Concat(val.Select(c => CharDictionary.ContainsKey(c) ? CharDictionary[c] : c)),
_ => val
};
19
Source : SjisTunnelEncoding.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
public override int GetByteCount(string str)
{
int byteCount = 0;
for (int i = 0; i < str.Length; i++)
{
bool tunneled = _mappings.ContainsKey(str[i]);
if (!tunneled)
{
try
{
_charArray[0] = str[i];
byteCount += SjisEncoding.GetByteCount(_charArray);
}
catch
{
tunneled = true;
}
}
if (tunneled)
byteCount += 2;
}
return byteCount;
}
19
Source : IgnoreCaseRelationGenerator.cs
with MIT License
from AutomataDotNet
with MIT License
from AutomataDotNet
private static Dictionary<char, BDD> ComputeIgnoreCaseDistionary(CharSetSolver solver)
{
var ignoreCase = new Dictionary<char, BDD>();
for (uint i = 0; i <= 0xFFFF; i++)
{
char c = (char)i;
char cU = char.ToUpper(c); // (char.IsLetter(char.ToUpper(c)) ? char.ToUpper(c) : c);
char cL = char.ToLower(c); // (char.IsLetter(char.ToLower(c)) ? char.ToLower(c) : c);
if (c != cU || c != cL || cU != cL)
{
//make sure that the regex engine considers c as being equivalent to cU and cL, else ignore c
//in some cases c != cU but the regex engine does not consider the chacarters equivalent wrt the ignore-case option.
//These characters are:
//c=\xB5,cU=\u039C
//c=\u0131,cU=I
//c=\u017F,cU=S
//c=\u0345,cU=\u0399
//c=\u03C2,cU=\u03A3
//c=\u03D0,cU=\u0392
//c=\u03D1,cU=\u0398
//c=\u03D5,cU=\u03A6
//c=\u03D6,cU=\u03A0
//c=\u03F0,cU=\u039A
//c=\u03F1,cU=\u03A1
//c=\u03F5,cU=\u0395
//c=\u1E9B,cU=\u1E60
//c=\u1FBE,cU=\u0399
if (System.Text.RegularExpressions.Regex.IsMatch(cU.ToString() + cL.ToString(), "^(?i:" + StringUtility.Escape(c) + ")+$"))
{
BDD equiv = solver.False;
if (ignoreCase.ContainsKey(c))
equiv = equiv | ignoreCase[c];
if (ignoreCase.ContainsKey(cU))
equiv = equiv | ignoreCase[cU];
if (ignoreCase.ContainsKey(cL))
equiv = equiv | ignoreCase[cL];
equiv = equiv | solver.MkCharSetFromRange(c, c) | solver.MkCharSetFromRange(cU, cU) | solver.MkCharSetFromRange(cL, cL);
foreach (char d in solver.GenerateAllCharacters(equiv))
ignoreCase[d] = equiv;
}
//else
//{
// outp += "c=" + StringUtility.Escape(c) + "," + "cU=" + StringUtility.Escape(cU);
// Console.WriteLine("c=" + StringUtility.Escape(c) + "," + "cL=" + StringUtility.Escape(cL) + "," + "cU=" + StringUtility.Escape(cU));
//}
}
}
return ignoreCase;
}
19
Source : Alfheim.cs
with MIT License
from betairylia
with MIT License
from betairylia
private void DoMCMCPreplaced()
{
PatternWeights weights = new PatternWeights(0.2f);
char[,,] mcmc_input = new char[gridSize.x, gridSize.y, gridSize.z];
gridBound = new BoundsInt(0, 0, 0, gridSize.x, gridSize.y, gridSize.z);
char[] charset = new char[2] { ' ', '*' };
// Read Map Data
foreach (var p in gridBound.allPositionsWithin)
{
SuperGrid sg = grids[p.x, p.y, p.z];
if (sg.type == GridType.SolidNature)// && Vector3.Dot(sg.groundNormal, Vector3.up) > 0.707f)
{
mcmc_input[p.x, p.y, p.z] = 'g';
}
else
{
mcmc_input[p.x, p.y, p.z] = '*';
// Above main road and cannot build
if (streetMap != null && streetMap[p.x * 4, p.z * 4] == '*' && p.y < 48)
{
mcmc_input[p.x, p.y, p.z] = 'b';
}
}
}
// Read Map Data
foreach (var p in gridBound.allPositionsWithin)
{
// Place a layer of buildings on top of nature
if (p.y > 0 &&
grids[p.x, p.y, p.z].type == GridType.Empty &&
grids[p.x, p.y - 1, p.z].type == GridType.SolidNature)
{
// Main road (on ground)
if(streetMap != null && streetMap[p.x * 4, p.z * 4] == '*')
{
mcmc_input[p.x, p.y - 1, p.z] = 'o';
}
else
{
// Randomly place some buildings
if(random.NextDouble() < 0.5)
{
mcmc_input[p.x, p.y, p.z] = ' ';
}
}
}
}
Alfheim_MCMCPreplaced preplaced = new Alfheim_MCMCPreplaced(
weights,
mcmc_input,
charset,
gridSize.x,
gridSize.y,
gridSize.z,
3
);
preplaced.temperature = temperature;
// Initial Visualization
#if DO_VISUALIZATION
#region Visualize
blockSet.Add(' ', new Block { id = 0x99dd66ff });
blockSet.Add('*', new Block { id = 0x00000000 }); // Air
blockSet.Add('o', new Block { id = 0x0077ffff });
blockSet.Add('r', new Block { id = 0xff0000ff });
blockSet.Add('g', new Block { id = 0x00ff00ff });
blockSet.Add('b', new Block { id = 0x00000000 }); // Air (Preserved)
foreach (var p in gridBound.allPositionsWithin)
{
SetBlock(bound.size - gridSize + p, blockSet[preplaced.map[p.x, p.y, p.z]]);
}
#endregion
#endif
preplaced.ResetCounters();
int epochs = mcmc_epochs;
int iters = mcmc_iters;
for(int i = 0; i < epochs; i++)
{
var ms = preplaced.BatchedStep(iters);
foreach (var m in ms)
{
if(!blockModifications.ContainsKey(m.to))
{
blockModifications[m.to] = 0;
}
blockModifications[m.to] += 1;
#if DO_VISUALIZATION
SetBlock(bound.size - gridSize + new Vector3Int(m.x, m.y, m.z), blockSet[m.to]);
#endif
}
if ((i % ((int)epochs / 10)) == 0)
{
Debug.Log($"Ep {i} Finished, Success {preplaced.success + preplaced.successRNG} (RNG {preplaced.successRNG}); Reject {preplaced.reject}; Reroll {preplaced.reroll}; E = {preplaced.prevEnergy}\n" +
$"Time: Proposal {preplaced.proposalTicks}, Pattern {preplaced.patternTicks}, ConnectionCopy {preplaced.connCopyTicks}, ConnectionUpdate {preplaced.connUpdateTicks}\n" +
$"{GetStr<char, int>(blockModifications)}");
}
#if DO_VISUALIZATION_CONNECTIVITY
for (int xx = gridBound.min.x; xx < gridBound.max.x; xx++)
{
for (int yy = gridBound.min.y; yy < gridBound.max.y; yy++)
{
int zz = 32;
Vector3Int p = new Vector3Int(xx, yy, zz);
uint val = (uint)(preplaced.connectivityMap[preplaced.flatten(xx, yy, zz)].distance);
val = val & 0xffff;
SetBlock(
bound.size - gridSize + p,
new Block { id = 0xFFFF, meta = (ushort)(((ushort)val << 4) | 0x000f) }
);
}
}
#endif
}
preplaced.Finish();
#if DO_VISUALIZATION
foreach (var p in gridBound.allPositionsWithin)
{
SetBlock(bound.size - gridSize + p, blockSet[preplaced.map[p.x, p.y, p.z]]);
}
#if DO_VISUALIZATION_CONNECTIVITY
for (int xx = gridBound.min.x; xx < gridBound.max.x; xx++)
{
for (int yy = gridBound.min.y; yy < gridBound.max.y; yy++)
{
int zz = 32;
Vector3Int p = new Vector3Int(xx, yy, zz);
uint val = (uint)(preplaced.connectivityMap[preplaced.flatten(xx, yy, zz)].distance);
val = val & 0xffff;
SetBlock(
bound.size - gridSize + p,
new Block { id = 0xFFFF, meta = (ushort)(((ushort)val << 4) | 0x000f) }
);
}
}
#endif
#endif
Debug.Log("MCMC Finished");
}
19
Source : MaskedTextField.razor.cs
with MIT License
from BlazorFluentUI
with MIT License
from BlazorFluentUI
private List<MaskValue> ParseMask(string mask, Dictionary<char, Regex> formatChars)
{
if (mask == null)
return new List<MaskValue>();
if (formatChars.Count == 0)
formatChars = ParsedMaskFormat;
List<MaskValue> maskCharData = new(mask.Length);
// Count the escape characters in the mask string.
int escapedChars = 0;
for (int i = 0; i + escapedChars < mask.Length; i++)
{
char maskChar = mask[i + escapedChars];
if (maskChar == '\\')
{
escapedChars++;
}
else
{
// Check if the maskChar is a format character.
if (formatChars.ContainsKey(maskChar))
{
Regex? maskFormat = formatChars[maskChar];
/**
///Do not add escapedChars to the displayIndex.
///The index refers to a position in the mask's displayValue.
///Since the backslashes don't appear in the displayValue,
///we do not add them to the charData displayIndex.
*/
maskCharData.Add(new() { DisplayIndex = i, Format = maskFormat });
}
}
}
return maskCharData;
}
19
Source : Utils.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
private static string sanitizeChar(char c, bool restricted)
{
if (restricted && accentChars.ContainsKey(c))
return accentChars[c];
else if (c == '?' || c < 32 || c == 127)
return "";
else if (c == '"')
return restricted ? "" : "\'";
else if (c == ':')
return restricted ? "_-" : " -";
else if ("\\/|*<>".Contains(c))
return "_";
else if (restricted && "!&\'()[]{}$;`^,# ".Contains(c))
return "_";
else if (restricted && c > 127)
return "_";
else return c.ToString();
}
19
Source : DemoJob.cs
with GNU General Public License v3.0
from bosima
with GNU General Public License v3.0
from bosima
public override string Collect(IEnumerable<JobTask> tasks)
{
Dictionary<char, int> stat = new Dictionary<char, int>();
foreach (var task in tasks)
{
// 自定义的任务结果字符串
var taskResult = task.Result;
if (!string.IsNullOrWhiteSpace(taskResult))
{
var taskStat = JsonConvert.DeserializeObject<Dictionary<char, int>>(taskResult);
foreach (var c in taskStat.Keys)
{
if (stat.ContainsKey(c))
{
stat[c] += taskStat[c];
}
else
{
stat[c] = taskStat[c];
}
}
}
}
// 如果结果太大,比如超过1G,写文件可能会很慢,请考虑写到别的地方去,这里返回个实际结果的地址就行了
// 返回字符串的格式自定义即可
return JsonConvert.SerializeObject(stat);
}
19
Source : DemoJob.cs
with GNU General Public License v3.0
from bosima
with GNU General Public License v3.0
from bosima
public override string ExecuteTask(JobTask task)
{
Dictionary<char, int> stat = new Dictionary<char, int>();
// 使用自己定义的需求
var requirement = task.Requirement;
if (requirement != null)
{
foreach (var c in requirement)
{
if (stat.ContainsKey(c))
{
stat[c]++;
}
else
{
stat.Add(c, 1);
}
}
}
// 测试超时的处理
Thread.Sleep(1 * 60 * 1000);
// 如果任务结果文件比较大,比如300M,会导致网速和内存占用较大,请考虑写到别的地方去,这里返回个实际结果的地址就行了
// 返回字符串的格式自定义即可
return JsonConvert.SerializeObject(stat);
}
19
Source : FileSystemInfoExtensions.cs
with MIT License
from bozho
with MIT License
from bozho
internal static void SetFileInfoAttributePattern(SetFileInfoAttributePattern setFileInfoAttributePattern) {
if (setFileInfoAttributePattern.DefaultPattern.IsPresent) {
sFileAttributePattern = sDefaultFileAttributePattern;
return;
}
sFileAttributePattern = (from p in setFileInfoAttributePattern.AttributePattern.ToCharArray()
let attr = Char.ToUpper(p)
where sFileAttributeChars.ContainsKey(attr)
select attr).ToArray();
}
19
Source : Sign.cs
with MIT License
from bradhannah
with MIT License
from bradhannah
private static string ScrubSignText(string signText)
{
char[] signTextArray = signText.ToArray();
string scrubbedStr = string.Empty;
// 8 = top left
// l = horizontal line
// m = top num
// 9 = top right
// g = vertical line
// n = bottom sign post
// : = bottom left
// ; = bottom right
// +)g = small sign top row
// f)* = small sign bottom row
// a = scrawly top left
// b = scrawly horizontal
// c = scrawly top right
// d = scrawly bottom left
// e = scrawly bottom horizontal (double line)
// f = scrawly bottom right
Dictionary<char, string> replacementChars = new Dictionary<char, string>
{
{ '@', " " },
{ '[', "TH" },
{ '^', "EA" },
{ '_', "ST" },
{ ']', "NG" },
{ '\\', "EE" }
};
// the actual character is a solid circle for separation //((char)0xA7).ToString());
char prevChar = '\0';
foreach (char signChar in signTextArray)
{
// do not translate lowercase because they are often used for drawing the actual signs
if (signChar >= 'A' && signChar <= 'Z' || signChar == ' ')
scrubbedStr += signChar;
else if (replacementChars.ContainsKey(signChar))
scrubbedStr += replacementChars[signChar];
// if we have two vertical bars then we move to the next line
else if (signChar == 'g' && prevChar == 'g')
// do nothing and leave it out
scrubbedStr += '\n';
else if (signChar > 127) scrubbedStr += ((char)(signChar - 128)).ToString();
prevChar = signChar;
}
return scrubbedStr;
}
19
Source : AtlasFont.cs
with MIT License
from ChevyRay
with MIT License
from ChevyRay
public AtlasChar AddChar(char chr, int width, int height, int advance, int offsetX, int offsetY, Rectangle uvRect, bool rotate90)
{
if (chars.ContainsKey(chr))
throw new Exception(string.Format("Font already has character: '{0}' (U+{1:X4})", chr, (UInt16)chr));
var name = chr.ToString();
AtlasImage image = null;
if (width > 0)
image = new AtlasImage(Atlas, ref name, width, height, offsetX, offsetY, width, height, ref uvRect, rotate90);
var result = new AtlasChar(this, chr, advance, image);
chars.Add(chr, result);
return result;
}
19
Source : StringExtensions.cs
with BSD 3-Clause "New" or "Revised" License
from china-live
with BSD 3-Clause "New" or "Revised" License
from china-live
public static string Translate(this string subject, char[] from, char[] to)
{
if (string.IsNullOrEmpty(subject))
{
return subject;
}
if (from == null || to == null)
{
throw new ArgumentNullException();
}
if (from.Length != to.Length)
{
throw new ArgumentNullException(nameof(from), "Parameters must have the same length");
}
var map = new Dictionary<char, char>(from.Length);
for (var i = 0; i < from.Length; i++)
{
map[from[i]] = to[i];
}
var result = new char[subject.Length];
for (var i = 0; i < subject.Length; i++)
{
var current = subject[i];
if (map.ContainsKey(current))
{
result[i] = map[current];
}
else
{
result[i] = current;
}
}
return new string(result);
}
19
Source : Parser.cs
with MIT License
from Chris3606
with MIT License
from Chris3606
private static List<string> toPostfix(string infix)
{
var output = new List<string>();
var operators = new Stack<char>();
int charIndex = 0;
while (charIndex < infix.Length)
{
if (char.IsDigit(infix[charIndex])) // Is an operand
{
string number = "";
while (charIndex < infix.Length && char.IsDigit(infix[charIndex]))
{
number += infix[charIndex];
charIndex++;
}
output.Add(number); // Add operand to postfix output
}
else // Separate so we can increment charIndex differently
{
if (infix[charIndex] == '(')
operators.Push(infix[charIndex]);
else if (infix[charIndex] == ')')
{
var op = operators.Pop();
while (op != '(')
{
output.Add(op.ToString());
op = operators.Pop();
}
}
else if (operatorPrecedence.ContainsKey(infix[charIndex]))
{
while (operators.Count > 0 && operatorPrecedence[operators.Peek()] >= operatorPrecedence[infix[charIndex]])
{
output.Add(operators.Pop().ToString());
}
operators.Push(infix[charIndex]);
}
charIndex++;
}
}
while (operators.Count != 0)
output.Add(operators.Pop().ToString());
return output;
}
19
Source : BitmapFont.cs
with MIT License
from Chroma-2D
with MIT License
from Chroma-2D
public bool HasGlyph(char c)
=> Glyphs.ContainsKey(c);
19
Source : TrueTypeFont.cs
with MIT License
from Chroma-2D
with MIT License
from Chroma-2D
public bool HasGlyph(char c)
=> _glyphs.ContainsKey(c);
19
Source : Query.cs
with MIT License
from codecov
with MIT License
from codecov
private static string EscapeKnownProblematicCharacters(string data)
{
var knownChars = new Dictionary<char, string>
{
{ '#', "%23" },
};
var result = new StringBuilder();
foreach (var c in data)
{
if (knownChars.ContainsKey(c))
{
result.Append(knownChars[c]);
}
else
{
result.Append(c);
}
}
return result.ToString();
}
19
Source : TextView.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
public int GetWidth(char ch, Font font)
{
if (!fontBoundCharWidth.ContainsKey(font)) {
fontBoundCharWidth.Add(font, new Dictionary<char, int>());
}
if (!fontBoundCharWidth[font].ContainsKey(ch)) {
using (Graphics g = textArea.CreateGraphics()) {
return GetWidth(g, ch, font);
}
}
return fontBoundCharWidth[font][ch];
}
19
Source : TextView.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
public int GetWidth(Graphics g, char ch, Font font)
{
if (!fontBoundCharWidth.ContainsKey(font)) {
fontBoundCharWidth.Add(font, new Dictionary<char, int>());
}
if (!fontBoundCharWidth[font].ContainsKey(ch)) {
//Console.WriteLine("Calculate character width: " + ch);
fontBoundCharWidth[font].Add(ch, MeasureStringWidth(g, ch.ToString(), font));
}
return fontBoundCharWidth[font][ch];
}
19
Source : NanoidTest.cs
with MIT License
from codeyu
with MIT License
from codeyu
[Fact]
public void TestFlatDistribution()
{
const int count = 100 * 1000;
var chars = new Dictionary<char, int>();
foreach (var dummy in Enumerable.Range(1, count))
{
var id = Nanoid.Generate();
for (var i = 0; i < DefaultSize; i++)
{
var c = id[i];
if (!chars.ContainsKey(c))
{
chars.Add(c, 0);
}
chars[c] += 1;
}
}
foreach (var c in chars)
{
var distribution = c.Value * DefaultAlphabet.Length / (double)(count * DefaultSize);
replacedert.True(ToBeCloseTo(distribution, 1, 1));
}
}
19
Source : Cheat.cs
with MIT License
from colinvella
with MIT License
from colinvella
public static bool IsValidGameGenieCode(string gameGenieCode)
{
if (gameGenieCode.Length != 6 && gameGenieCode.Length != 8)
return false;
foreach (char ch in gameGenieCode)
if (!gameGenieCharToNybble.ContainsKey(ch))
return false;
return true;
}
19
Source : CipParser.cs
with MIT License
from CoreOpenMMO
with MIT License
from CoreOpenMMO
public static Stack<string> GetEnclosedButPreserveQuoted(string str, Dictionary<char, char> openClosePairs)
{
var stack = new Stack<string>();
if (string.IsNullOrWhiteSpace(str))
{
return stack;
}
var openEnclosure = new Stack<char>();
var buffers = new Stack<StringBuilder>();
var main = new StringBuilder();
buffers.Push(main);
var inQuote = false;
for (var i = 0; i < str.Length; i++)
{
if (str[i] == Quote && (i > 0 && str[i - 1] != '\\'))
{
inQuote = !inQuote;
}
var c = str[i];
if (openClosePairs.ContainsValue(c) && !inQuote)
{
openEnclosure.Push(c);
buffers.Push(new StringBuilder());
}
else if (openClosePairs.ContainsKey(c) && !inQuote)
{
if (openEnclosure.Peek() != openClosePairs[c])
{
throw new Exception("Malformed string.");
}
openEnclosure.Pop();
stack.Push(buffers.Pop().ToString());
}
else
{
buffers.Peek().Append(c);
}
}
while (buffers.Count > 0)
{
stack.Push(buffers.Pop().ToString());
}
return stack;
}
19
Source : StringUtilities.cs
with MIT License
from corycorvus
with MIT License
from corycorvus
public static string TrimSpecialFormatting(string input, HashSet<char> charsToRemove,
HashSet<char> leadingCharsForWordsToRemove, Dictionary<char, char> surroundingCharsForTextToRemove,
bool removeAllNonAlphanumericOrWhitespaceChars = true, bool removeExtraWhitespace = true)
{
string output = "";
if (input.Length > 0)
{
int startIndex = 0;
int endIndex = input.Length - 1;
if (removeExtraWhitespace)
{
// Skip whitespace at the beginning and end.
while (startIndex < input.Length && char.IsWhiteSpace(input[startIndex]))
{
startIndex++;
}
while (endIndex >= 0 && char.IsWhiteSpace(input[endIndex]))
{
endIndex--;
}
}
bool currentlyIgnoringWhitespace = false;
bool currentlyInWordToRemove = false;
const char wordSeparatorChar = ' ';
char lastAddedChar = wordSeparatorChar;
bool currentlyInTextToRemove = false;
char endCharForCurrentTextToRemove = '\0';
for (int i = startIndex; i <= endIndex; ++i)
{
// Ignore all characters as long as we are still within text to remove.
if (currentlyInTextToRemove)
{
if (input[i] == endCharForCurrentTextToRemove)
{
currentlyInTextToRemove = false;
}
}
// Otherwise we might still add this character.
else
{
// If we were within a word to remove and the current character is a word separator character,
// then we are no longer within a word to remove.
if (currentlyInWordToRemove && input[i] == wordSeparatorChar)
{
currentlyInWordToRemove = false;
}
// If we are not within a word to remove and either we are not ignoring whitespace
// or this character is not whitespace, we might still add this character.
if (!currentlyInWordToRemove && (!currentlyIgnoringWhitespace || !char.IsWhiteSpace(input[i])))
{
// If this character is the leading character for text to remove, then we are now within text to remove.
if (surroundingCharsForTextToRemove.ContainsKey(input[i]))
{
currentlyInTextToRemove = true;
endCharForCurrentTextToRemove = surroundingCharsForTextToRemove[input[i]];
}
// If this character is both the first character in a word and the leading character
// for a word to remove, then we are now within a word to remove.
else if (leadingCharsForWordsToRemove.Contains(input[i]) && (i == 0 || lastAddedChar == wordSeparatorChar))
{
currentlyInWordToRemove = true;
}
// If this character isn't one of the given characters to remove, we might still add this character.
else if (!charsToRemove.Contains(input[i])
&& (!removeAllNonAlphanumericOrWhitespaceChars || char.IsLetterOrDigit(input[i]) || char.IsWhiteSpace(input[i])))
{
// If we are not ignoring whitespace or this character is not whitespace, add this character.
if (!currentlyIgnoringWhitespace || !char.IsWhiteSpace(input[i]))
{
output += input[i];
lastAddedChar = input[i];
}
// Determine if we should start ignoring whitespace or stop ignoring whitespace.
if (!currentlyIgnoringWhitespace && char.IsWhiteSpace(input[i]) && removeExtraWhitespace)
{
currentlyIgnoringWhitespace = true;
}
else if (currentlyIgnoringWhitespace && !char.IsWhiteSpace(input[i]))
{
currentlyIgnoringWhitespace = false;
}
}
}
}
}
}
SmartLogger.Log(DebugFlags.StringUtilities, "Original String: " + input);
SmartLogger.Log(DebugFlags.StringUtilities, "Trimmed String: " + output);
return output;
}
19
Source : Tokenizer.cs
with MIT License
from craigbridges
with MIT License
from craigbridges
public string[] Tokenize
(
string value
)
{
// Remove extra white space before tokenizing
value = value.Trim().Replace
(
" ",
" "
);
var tokens = new List<string>();
var tokenBuilder = new StringBuilder();
var newToken = true;
var enclosures = this.Enclosures;
var enclosureQueue = new Stack<char>();
var index = 0;
foreach (var c in value)
{
if (newToken)
{
// Start a new token when the builder is empty
if (c != this.Separator)
{
tokenBuilder.Append(c);
}
if (enclosures.ContainsKey(c))
{
var containsClosing = value.Substring(index).Contains
(
enclosures[c].ToString()
);
// Only enqueue the enclosure if the remaining string has it
if (containsClosing)
{
enclosureQueue.Push
(
enclosures[c]
);
}
else
{
enclosureQueue.Push
(
this.Separator
);
}
}
else
{
enclosureQueue.Push
(
this.Separator
);
}
newToken = false;
}
else
{
var tokenComplete = false;
// Check if this character is an ending enclosure
if (enclosureQueue.Any() && enclosureQueue.Peek() == c)
{
enclosureQueue.Pop();
if (enclosureQueue.Count == 0)
{
tokenComplete = true;
}
}
else if (enclosures.ContainsKey(c))
{
var containsClosing = value.Substring(index).Contains
(
enclosures[c].ToString()
);
// Only enqueue the enclosure if the remaining string has it
if (containsClosing)
{
enclosureQueue.Push
(
enclosures[c]
);
}
}
if (false == tokenComplete || c != this.Separator)
{
tokenBuilder.Append(c);
}
// Check if we should flush the current token
if (tokenComplete)
{
tokens.Add
(
tokenBuilder.ToString().Trim()
);
tokenBuilder.Clear();
newToken = true;
}
}
index++;
}
if (tokenBuilder.Length > 0)
{
tokens.Add
(
tokenBuilder.ToString().Trim()
);
}
return tokens.ToArray();
}
19
Source : Bitap.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
private BitapResult GetBitapSearch(string text)
{
var expectedLocation = _options.location;
var textLen = text.Length;
var currentThreshold = _options.threshold;
var bestLocation = text.IndexOf(_pattern, expectedLocation);
var patternLen = _pattern.Length;
var matchMask = new int[textLen];
var score = 0f;
for (var i = 0; i < textLen; i++)
{
matchMask[i] = 0;
}
if (bestLocation != -1)
{
score = GetScore(new BitapScoreOpts
{
errors = 0,
currentLocation = bestLocation,
expectedLocation = expectedLocation,
distance = _options.distance
});
currentThreshold = Math.Min(score, currentThreshold);
bestLocation = text.LastIndexOf(_pattern, expectedLocation + patternLen);
if (bestLocation != -1)
{
score = GetScore(new BitapScoreOpts
{
errors = 0,
currentLocation = bestLocation,
expectedLocation = expectedLocation,
distance = _options.distance
});
currentThreshold = Math.Min(score, currentThreshold);
}
}
bestLocation = -1;
float finalScore = 1f;
int[] lastBitArr = new int[textLen];
var binMax = patternLen + textLen;
var mask = 1 << (patternLen <= 31 ? patternLen - 1 : 30);
for (var i = 0; i < patternLen; i += 1)
{
var binMin = 0;
var binMid = binMax;
while (binMin < binMid)
{
score = GetScore(new BitapScoreOpts
{
errors = i,
currentLocation = expectedLocation + binMid,
expectedLocation = expectedLocation,
distance = _options.distance
});
if (score <= currentThreshold)
{
binMin = binMid;
}
else
{
binMax = binMid;
}
binMid = (int)Math.Floor((binMax - binMin) / 2f + binMin);
}
binMax = binMid;
var start = Math.Max(1, expectedLocation - binMid + 1);
var finish = _options.findAllMatches ? textLen : Math.Min(expectedLocation + binMid, textLen) + patternLen;
var bitArr = new int[finish + 2];
bitArr[finish + 1] = (1 << i) - 1;
for (var j = finish; j >= start; j--)
{
var currentLocation = j - 1;
var charMatch = 0;
if (currentLocation < text.Length)
{
var textChar = text[currentLocation];
if (_alphabet.ContainsKey(textChar) && _alphabet[textChar] > 0)
{
matchMask[currentLocation] = 1;
}
}
bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch;
if (i != 0)
{
bitArr[j] |= (((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1) | lastBitArr[j + 1];
}
if (bitArr[j] > 0 & mask > 0)
{
finalScore = GetScore(new BitapScoreOpts
{
errors = i,
currentLocation = currentLocation,
expectedLocation = expectedLocation,
distance = _options.distance
});
if (finalScore <= currentThreshold)
{
currentThreshold = finalScore;
bestLocation = currentLocation;
if (bestLocation <= expectedLocation)
{
break;
}
start = Math.Max(1, 2 * expectedLocation - bestLocation);
}
}
}
score = GetScore(new BitapScoreOpts
{
errors = i + 1,
currentLocation = expectedLocation,
expectedLocation = expectedLocation,
distance = _options.distance
});
if (score > currentThreshold)
{
break;
}
lastBitArr = bitArr;
}
var result = new BitapResult
{
isMatch = (bestLocation >= 0),
score = (finalScore == 0f ? 0.001f : finalScore),
matchedIndices = GetMatchedIndices(matchMask)
};
return result;
}
19
Source : TextManager.cs
with MIT License
from csinkers
with MIT License
from csinkers
public PositionedSpriteBatch BuildRenderable(TextBlock block, DrawLayer order, Rectangle? scissorRegion, object caller)
{
if (block == null) throw new ArgumentNullException(nameof(block));
var replacedets = Resolve<IreplacedetManager>();
var sm = Resolve<ISpriteManager>();
var window = Resolve<IWindowManager>();
var font = replacedets.LoadFont(block.Color, block.Style == TextStyle.Big);
var mapping = GetFontMapping(font.Id, replacedets);
var text = block.Text ?? "";
var isFat = block.Style is TextStyle.Fat or TextStyle.FatAndHigh;
int offset = 0;
var flags = SpriteKeyFlags.NoTransform | SpriteKeyFlags.NoDepthTest;
var key = new SpriteKey(font, SpriteSampler.Point, order, flags, scissorRegion);
int displayableCharacterCount = text.Count(x => mapping.ContainsKey(x));
int instanceCount = displayableCharacterCount * (isFat ? 4 : 2);
var lease = sm.Borrow(key, instanceCount, caller);
bool lockWasTaken = false;
var instances = lease.Lock(ref lockWasTaken);
try
{
int n = 0;
foreach (var c in text)
{
if (!mapping.TryGetValue(c, out var index)) { offset += SpaceSize; continue; } // Spaces etc
var subImage = font.Regions[index];
// Adjust texture coordinates slightly to avoid bleeding
// var texOffset = subImage.TexOffset.Y + 0.1f / font.Height;
var normPosition = window.UiToNormRelative(offset, 0);
var baseInstance = new SpriteInstanceData(
new Vector3(normPosition, 0),
window.UiToNormRelative(subImage.Size),
subImage, SpriteFlags.TopLeft);
instances[n] = baseInstance;
instances[n + 1] = baseInstance;
if (isFat)
{
instances[n + 2] = baseInstance;
instances[n + 3] = baseInstance;
instances[n].OffsetBy(new Vector3(window.UiToNormRelative(2, 1), 0));
instances[n].Flags |= SpriteFlags.DropShadow;
instances[n + 1].OffsetBy(new Vector3(window.UiToNormRelative(1, 1), 0));
instances[n + 1].Flags |= SpriteFlags.DropShadow;
instances[n + 2].OffsetBy(new Vector3(window.UiToNormRelative(1, 0), 0));
offset += 1;
}
else
{
instances[n].Flags |= SpriteFlags.DropShadow;
instances[n].OffsetBy(new Vector3(window.UiToNormRelative(1, 1), 0));
}
offset += (int)subImage.Size.X;
n += isFat ? 4 : 2;
}
}
finally { lease.Unlock(lockWasTaken); }
var fontSize = font.Regions[0].Size;
var size = new Vector2(offset + 1, fontSize.Y + 1); // +1 for the drop shadow
return new PositionedSpriteBatch(lease, size);
}
19
Source : ValidDtmfs.cs
with MIT License
from CXuesong
with MIT License
from CXuesong
public static void Validate(char digit)
{
Utils.replacedertArgument(ValidDtmfSet.ContainsKey(digit), "'{0}' is not a valid dtmf", digit);
}
19
Source : CMapInfo.cs
with MIT License
from damienbod
with MIT License
from damienbod
internal bool Contains(char ch)
{
return CharacterToGlyphIndex.ContainsKey(ch);
}
19
Source : CMapInfo.cs
with MIT License
from damienbod
with MIT License
from damienbod
public void AddChars(string text)
{
if (text != null)
{
bool symbol = _descriptor.FontFace.cmap.symbol;
int length = text.Length;
for (int idx = 0; idx < length; idx++)
{
char ch = text[idx];
if (!CharacterToGlyphIndex.ContainsKey(ch))
{
char ch2 = ch;
if (symbol)
{
// Remap ch for symbol fonts.
ch2 = (char)(ch | (_descriptor.FontFace.os2.usFirstCharIndex & 0xFF00)); // @@@ refactor
}
int glyphIndex = _descriptor.CharCodeToGlyphIndex(ch2);
CharacterToGlyphIndex.Add(ch, glyphIndex);
GlyphIndices[glyphIndex] = null;
MinChar = (char)Math.Min(MinChar, ch);
MaxChar = (char)Math.Max(MaxChar, ch);
}
}
}
}
19
Source : NumberLiteral.cs
with MIT License
from daxnet
with MIT License
from daxnet
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) {
//remember start - it may be different from source.TokenStart, we may have skipped prefix
int start = source.PreviewPosition;
char current = source.PreviewChar;
if (IsSet(NumberOptions.AllowSign) && (current == '-' || current == '+')) {
details.Sign = current.ToString();
source.PreviewPosition++;
}
//Figure out digits set
string digits = GetDigits(details);
bool isDecimal = !details.IsSet((short) (NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex));
bool allowFloat = !IsSet(NumberOptions.IntOnly);
bool foundDigits = false;
while (!source.EOF()) {
current = source.PreviewChar;
//1. If it is a digit, just continue going; the same for '_' if it is allowed
if (digits.IndexOf(current) >= 0 || IsSet(NumberOptions.AllowUnderscore) && current == '_') {
source.PreviewPosition++;
foundDigits = true;
continue;
}
//2. Check if it is a dot in float number
bool isDot = current == DecimalSeparator;
if (allowFloat && isDot) {
//If we had seen already a dot or exponent, don't accept this one;
bool hasDotOrExp = details.IsSet((short) (NumberFlagsInternal.HasDot | NumberFlagsInternal.HasExp));
if (hasDotOrExp) break; //from while loop
//In python number literals (NumberAllowPointFloat) a point can be the first and last character,
//We accept dot only if it is followed by a digit
if (digits.IndexOf(source.NextPreviewChar) < 0 && !IsSet(NumberOptions.AllowStartEndDot))
break; //from while loop
details.Flags |= (int) NumberFlagsInternal.HasDot;
source.PreviewPosition++;
continue;
}
//3. Check if it is int number followed by dot or exp symbol
bool isExpSymbol = (details.ExponentSymbol == null) && _exponentsTable.ContainsKey(current);
if (!allowFloat && foundDigits && (isDot || isExpSymbol)) {
//If no partial float allowed then return false - it is not integer, let float terminal recognize it as float
if (IsSet(NumberOptions.NoDotAfterInt)) return false;
//otherwise break, it is integer and we're done reading digits
break;
}
//4. Only for decimals - check if it is (the first) exponent symbol
if (allowFloat && isDecimal && isExpSymbol) {
char next = source.NextPreviewChar;
bool nextIsSign = next == '-' || next == '+';
bool nextIsDigit = digits.IndexOf(next) >= 0;
if (!nextIsSign && !nextIsDigit)
break; //Exponent should be followed by either sign or digit
//ok, we've got real exponent
details.ExponentSymbol = current.ToString(); //remember the exp char
details.Flags |= (int) NumberFlagsInternal.HasExp;
source.PreviewPosition++;
if (nextIsSign)
source.PreviewPosition++; //skip +/- explicitly so we don't have to deal with them on the next iteration
continue;
}
//4. It is something else (not digit, not dot or exponent) - we're done
break; //from while loop
}//while
int end = source.PreviewPosition;
if (!foundDigits)
return false;
details.Body = source.Text.Substring(start, end - start);
return true;
}
19
Source : LcdCharacterEncodingFactory.cs
with MIT License
from dotnet
with MIT License
from dotnet
private bool replacedignLettersForCurrentCulture(Dictionary<char, byte> characterMapping, CultureInfo culture, string romName, List<byte[]> extraCharacters, int maxNumberOfCustomCharacters)
{
string specialLetters = SpecialLettersForCulture(culture, characterMapping); // Special letters this language group uses, in order of importance
byte charPos = 0;
foreach (var c in specialLetters)
{
if (!characterMapping.ContainsKey(c))
{
// This letter doesn't exist, insert it
if (charPos < maxNumberOfCustomCharacters)
{
var pixelMap = CreateLetter(c, romName);
if (pixelMap is object)
{
extraCharacters.Add(pixelMap);
characterMapping.Add(c, charPos);
charPos++;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
return true;
}
19
Source : Pcd8544.cs
with MIT License
from dotnet
with MIT License
from dotnet
public void CreateCustomCharacter(int location, ReadOnlySpan<byte> characterMap)
{
if (location >= NumberOfCustomCharactersSupported)
{
throw new ArgumentException($"{location} can only be smaller than {NumberOfCustomCharactersSupported}");
}
if (characterMap.Length is not 8 or 5)
{
throw new ArgumentException($"Character can only be 8 or 5 bytes array");
}
byte[] character = characterMap.Length == 8 ?
LcdCharacterEncodingFactory.ConvertFont8to5bytes(characterMap.ToArray()) :
characterMap.ToArray();
if (_font.ContainsKey((char)location))
{
_font.Remove((char)location);
}
_font.Add((char)location, character);
}
19
Source : Pcd8544.cs
with MIT License
from dotnet
with MIT License
from dotnet
private void WriteChar(char c)
{
Span<byte> letter = stackalloc byte[CharacterWidth];
bool isChar = _font.ContainsKey(c);
if (isChar)
{
if (isChar)
{
byte[] font = _font[c];
for (int i = 0; i < CharacterWidth - 1; i++)
{
letter[i] = font[i];
}
}
letter[5] = 0x00;
letter.CopyTo(_byteMap.replacedpan(_position));
SpiWrite(true, letter);
_position += CharacterWidth;
}
else if (c == 0x08)
{
// Case of backspace, we go back
if (_cursorVisible)
{
DrawCursor();
}
_position -= CharacterWidth;
_position = _position < 0 ? 0 : _position;
SetPosition(_position);
SpiWrite(true, letter);
letter.CopyTo(_byteMap.replacedpan(_position));
SetPosition(_position);
}
}
19
Source : TextNormalizing.cs
with MIT License
from dotnet
with MIT License
from dotnet
private void NormalizeSrc(in ReadOnlyMemory<char> src, ref ReadOnlyMemory<char> dst, StringBuilder buffer)
{
Host.replacedertValue(buffer);
if (src.IsEmpty)
{
dst = src;
return;
}
buffer.Clear();
int i = 0;
int min = 0;
var span = src.Span;
while (i < src.Length)
{
char ch = span[i];
if (!_parent._keepPunctuations && char.IsPunctuation(ch) || !_parent._keepNumbers && char.IsNumber(ch))
{
// Append everything before ch and ignore ch.
buffer.AppendSpan(span.Slice(min, i - min));
min = i + 1;
i++;
continue;
}
if (!_parent._keepDiacritics)
{
if (IsCombiningDiacritic(ch))
{
buffer.AppendSpan(span.Slice(min, i - min));
min = i + 1;
i++;
continue;
}
if (CombinedDiacriticsMap.ContainsKey(ch))
ch = CombinedDiacriticsMap[ch];
}
if (_parent._caseMode == TextNormalizingEstimator.CaseMode.Lower)
ch = CharUtils.ToLowerInvariant(ch);
else if (_parent._caseMode == TextNormalizingEstimator.CaseMode.Upper)
ch = CharUtils.ToUpperInvariant(ch);
if (ch != src.Span[i])
{
buffer.AppendSpan(span.Slice(min, i - min)).Append(ch);
min = i + 1;
}
i++;
}
Host.replacedert(i == src.Length);
int len = i - min;
if (min == 0)
{
Host.replacedert(src.Length == len);
dst = src;
}
else
{
buffer.AppendSpan(span.Slice(min, len));
dst = buffer.ToString().AsMemory();
}
}
19
Source : TextFormatterContext.cs
with MIT License
from dotnet
with MIT License
from dotnet
static internal bool IsSpecialCharacter(char c)
{
return _specialCharacters.ContainsKey(c);
}
19
Source : PixelFont.cs
with MIT License
from dotnet-ad
with MIT License
from dotnet-ad
public void Draw(SpriteBatch spriteBatch, Vector2 position, string message, Color color, int fontSize = 10)
{
var scale = fontSize / 5.0f;
var x = position.X;
var y = position.Y;
message = message.ToUpper();
foreach (var c in message)
{
if (c == ' ')
{
x += LetterSpace + Space;
}
else if (c == '\n')
{
y += LineSpace + fontSize;
x = position.X;
}
else if(this.Textures.ContainsKey(c))
{
var texture = this.Textures[c];
spriteBatch.Draw(texture, new Vector2(x, y), color: color, scale: Vector2.One * scale);
x += (int)((((x > 0) ? LetterSpace : 0) + texture.Width) * scale);
}
}
}
19
Source : PrecisionMinPriorityTree.cs
with MIT License
from dotnet-lab
with MIT License
from dotnet-lab
private void AddFrequencyToTripCache()
{
//统计每个字符在当前位置出现的次数
//遍历最大字符长度
for (int i = 0; i < MaxLength; i += 1)
{
//遍历trip字符缓存
Dictionary<char, int> charsCache = new Dictionary<char, int>();
foreach (var item in TripCache)
{
//如果当前字符串的长度大于索引
if (item.Key.Length > i)
{
//获取字符
var tempChar = item.Key[i];
if (charsCache.ContainsKey(tempChar))
{
//如果缓存里已经存在了字符,那么缓存计数+1
charsCache[tempChar] += 1;
}
else
{
//否则设置缓存字符,计数默认为1
charsCache[tempChar] = 1;
}
}
}
//把之前位置对应的字符出现的频率,写入缓存中
//再一次遍历trip字符缓存
foreach (var item in TripCache)
{
//如果当前字符串的长度大于索引
if (item.Key.Length > i)
{
//设置当前层字符的匹配频次
int matchCount = charsCache[item.Key[i]];
item.Value.RepeateCache[i] = matchCount;
//记录频次最大值
if (MaxMatchCount < matchCount)
{
MaxMatchCount = matchCount;
}
}
}
}
}
19
Source : Font.cs
with MIT License
from drjaydenm
with MIT License
from drjaydenm
private Glyph GetGlyphByCharacter(char character)
{
if (loadedGlyphs.ContainsKey(character))
return loadedGlyphs[character];
var glyphIndex = typeface.GetGlyphIndex(character);
var glyph = typeface.GetGlyph(glyphIndex);
loadedGlyphs.Add(character, glyph);
return glyph;
}
19
Source : VeldridTextRenderer.cs
with MIT License
from drjaydenm
with MIT License
from drjaydenm
public void DrawText(string text, Vector2 coordsInPixels, Color color, float letterSpacing)
{
var drawable = new DrawableText
{
Text = text,
Glyphs = new DrawableGlyph[text.Length],
Position = coordsInPixels,
Color = color,
LetterSpacing = letterSpacing
};
var measurementInfo = Font.GetMeasurementInfoForString(text);
var acreplacedulatedAdvanceWidths = 0f;
drawable.Rectangle.Reset();
var stringVertices = Font.GetVerticesForString(text);
for (var i = 0; i < text.Length; i++)
{
if (cachedGlyphs.ContainsKey(text[i]))
{
drawable.Glyphs[i] = cachedGlyphs[text[i]];
acreplacedulatedAdvanceWidths += measurementInfo.AdvanceWidths[i];
continue;
}
var vertices = stringVertices.Vertices[i];
// Extend the text rectangle to contain this letter
for (var j = 0; j < vertices.Length; j++)
{
drawable.Rectangle.Include(vertices[j].Position.X + acreplacedulatedAdvanceWidths, vertices[j].Position.Y);
}
var drawableGlyph = new DrawableGlyph
{
Vertices = vertices,
AdvanceX = measurementInfo.AdvanceWidths[i]
};
drawable.Glyphs[i] = drawableGlyph;
cachedGlyphs.Add(text[i], drawableGlyph);
acreplacedulatedAdvanceWidths += measurementInfo.AdvanceWidths[i];
}
textToDraw.Add(drawable);
}
19
Source : MakeTrans.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public string Translate(string src)
{
var sb = new StringBuilder(src.Length);
foreach (var srcC in src)
sb.Append(_dic.ContainsKey(srcC) ? _dic[srcC] : srcC);
return sb.ToString();
}
19
Source : ScrollableTextBlock.cs
with GNU General Public License v2.0
from evgeny-nadymov
with GNU General Public License v2.0
from evgeny-nadymov
private void SplitText(string text)
{
while (true)
{
var symbolsCount = Math.Min(MaxSymbolsChunk, text.Length);
var stepsBack = 0;
if (symbolsCount != text.Length)
{
if (!Delimiters.ContainsKey(text[symbolsCount - 1]))
{
for (var i = 1; i < 24 && (symbolsCount - 1 - i) >= 0; i++)
{
if (Delimiters.ContainsKey(text[symbolsCount - 1 - i]))
{
stepsBack += i;
break;
}
}
}
}
symbolsCount -= stepsBack;
var currentChunk = text.Substring(0, symbolsCount);
AddTextChunk(currentChunk);
var nextChunk = text.Substring(symbolsCount, text.Length - symbolsCount);
if (nextChunk.Length > 0)
{
text = nextChunk;
continue;
}
break;
}
}
19
Source : Language.cs
with GNU General Public License v2.0
from evgeny-nadymov
with GNU General Public License v2.0
from evgeny-nadymov
public static string TransliterateToRussian(string str)
{
var enStr = new StringBuilder();
foreach (var alpha in str)
{
if (_enRuTable.ContainsKey(alpha))
{
enStr.Append(_enRuTable[alpha]);
}
}
return enStr.ToString();
}
19
Source : Language.cs
with GNU General Public License v2.0
from evgeny-nadymov
with GNU General Public License v2.0
from evgeny-nadymov
public static string TransliterateToEnglish(string str)
{
var enStr = new StringBuilder();
foreach (var alpha in str)
{
if (_ruEnTable.ContainsKey(alpha))
{
enStr.Append(_ruEnTable[alpha]);
}
}
return enStr.ToString();
}
19
Source : Language.cs
with GNU General Public License v2.0
from evgeny-nadymov
with GNU General Public License v2.0
from evgeny-nadymov
public static string Transliterate(string str)
{
var enCount = 0;
var ruCount = 0;
var count = 0;
const int maxCount = 7;
foreach (var alpha in str)
{
if (count > maxCount) break;
if (_enRuTable.ContainsKey(alpha))
{
enCount++;
}
else if (_ruEnTable.ContainsKey(alpha))
{
ruCount++;
}
count++;
}
if (enCount > ruCount)
{
return TransliterateToRussian(str);
}
return TransliterateToEnglish(str);
}
See More Examples