public static byte[] parseKey(String parseThis) { String toParse = parseThis.Trim(); byte[] toReturn = new byte[toParse.Length/2]; foreach (char thisChar in parseThis.ToCharArray()) { if (thisChar < '0') return null; if (thisChar > '9' && thisChar < 'A') throw null; if (thisChar > 'Z' && thisChar < 'a') throw null; if (thisChar > 'z') throw null; } int charPos = 0; Char[] toConvert = toParse.ToCharArray(); for (int keyPos = 0; keyPos < toReturn.Length; keyPos++) { Char higherVal = toConvert[charPos + 0]; Char lowerVal = toConvert[charPos + 1]; toReturn[keyPos] = hexCharToValChar(lowerVal, higherVal); charPos += 2; } return toReturn; }
// GET: Terminal/Edit/5 public ActionResult RunCommand(String input) { char[] charArray = input.ToCharArray(); Array.Reverse(charArray); string reversed = new string(charArray); return Content(reversed); }
/// <summary> /// Takes an input string from the weather board and returns an array /// of doubles. /// /// </summary> /// <param name="input"></param> /// <returns></returns> public static double[] ConvertWeatherInput(String input) { double[] values = new double[8]; StringBuilder working = new StringBuilder(); int position = -1; foreach (char c in input.ToCharArray()) { if (position < 0) { if (c == '#') { position = 0; } } else { if (c == '$') { break; } else if (c == ',') { values[position] = Double.Parse(working.ToString()); position++; working.Clear(); } else { working.Append(c); } } } return values; }
public static FilterResult FilterBannedWorlds(List<String> bannedWorlds, String text, bool replace, bool caseSensitive) //! case sensitive { int count = 0; bool[] upperCases = new bool[text.Length]; char[] charText = text.ToCharArray (); if (!caseSensitive) //detection of the upper case to replace them at the end { for (int i = 0; i < charText.Length ; ++i) { if (char.IsUpper (charText [i])) { upperCases [i] = true; } else { upperCases [i] = false; } } text = text.ToLower (); //lower all the text ! } foreach (String bannedWorld in bannedWorlds) //loop on the bad worlds list { count += Regex.Matches(text, bannedWorld).Count; //count the negative worlds if (replace) //replace them if asked { string replacedbannedWorld = ReplaceWorld (bannedWorld); text = text.Replace (bannedWorld, replacedbannedWorld); } } if (!caseSensitive) //the text is lower -> we have to put back the upper cases { charText = text.ToCharArray (); for (int i = 0; i < charText.Length ; ++i) { if (upperCases [i]) { charText [i] = char.ToUpper (charText [i]); } else { charText [i] = char.ToLower (charText [i]); } } text = new String(charText); } return new FilterResult (text, count); }
public void setConnected(String s) { if (s.Length > 1) { connected = ((int)s.ToCharArray()[0]) + "/" + ((int)s.ToCharArray()[1]); } else { connected = "0/" + (int)s.ToCharArray()[0]; } }
string ifade_temizle(String str) { string karar_metni = ""; for (int i = 0; i < str.Length; i++) { if (str.ToCharArray()[i] == ' ') { continue; } karar_metni += str.ToCharArray()[i]; } return degiskenleriKoy(karar_metni); }
public static String Crypt(String encryptText, int shift) { String endString = ""; int encryptStringLength = encryptText.Length; for (int i = 0; i < encryptStringLength; i++) { if (encryptText.ToCharArray()[i].Equals('1')) { throw new ArgumentOutOfRangeException(); } endString += CryptChar(encryptText.ToCharArray()[i], shift); } return endString; }
int MotorolaLicence_check(String company, String licence) { char[] wtCoName = company.ToCharArray(); char[] wtReg = licence.ToCharArray(); int iChecksum = 0; for(uint iCS=0; iCS<wtCoName.Length; iCS++) iChecksum+=wtCoName[iCS]; if(iChecksum > 0xEE2) return 0; char[] wtDecrypted = new char[50]; char[] wtCS = new char[5]; char[] wtLicenseKey = new char[16]; wsprintf(wtCS, "%03X:", iChecksum); wtDIN = "CORPERATELICENSE"; DecryptPwd(ref wtReg, ref wtDecrypted); if(wcsncmp(wtCS, wtDecrypted, 4) != 0) return 0; wsprintf(wtLicenseKey, "%s%d_%dO0", LIC_KEY, dwVer1, dwVer2, dwVer3); if(wcscmp(wtDecrypted,wtLicenseKey ) != 0)//todo!!! return 0; return 1; }
public static String GetStringWith(String str, int length) { str = str.PadRight(length, " "[0]); char [] strs = str.ToCharArray(); str = ""; int i = 0; foreach (char s in strs) { str = str + s.ToString(); i = i + Encoding.Default.GetByteCount(s.ToString()); if (i == length || i == length -1 ) { str = str.Substring(0, str.Length - 2) + " "; break; } } str = str.PadRight(length, " "[0]); int bytecount = Encoding.Default.GetByteCount(str); int strlength = str.Length; int zh_count = bytecount - strlength; str = str.Substring(0, length - zh_count); return str; }
static String ReplaceSpace(String s) { char[] a = s.ToCharArray(); int endPointer = a.Length - 1; int nonSpacePointer = a.Length - 1; while (a[nonSpacePointer] == ' ') nonSpacePointer--; while (endPointer != 0) { if (a[nonSpacePointer] != ' ') { a[endPointer] = a[nonSpacePointer]; endPointer--; } else { a[endPointer] = '0'; endPointer--; a[endPointer] = '2'; endPointer--; a[endPointer] = '%'; endPointer--; } nonSpacePointer--; } return new String(a); }
/** * Escapes a string with the appropriated XML codes. * @param s the string to be escaped * @param onlyASCII codes above 127 will always be escaped with &#nn; if <CODE>true</CODE> * @return the escaped string * @since 5.0.6 */ public static String EscapeXML(String s, bool onlyASCII) { char[] cc = s.ToCharArray(); int len = cc.Length; StringBuilder sb = new StringBuilder(); for (int k = 0; k < len; ++k) { int c = cc[k]; switch (c) { case '<': sb.Append("<"); break; case '>': sb.Append(">"); break; case '&': sb.Append("&"); break; case '"': sb.Append("""); break; case '\'': sb.Append("'"); break; default: if (IsValidCharacterValue(c)) { if (onlyASCII && c > 127) sb.Append("&#").Append(c).Append(';'); else sb.Append((char)c); } break; } } return sb.ToString(); }
// takes a line of text document as a String and stores its info public void processAnswerTextLine(String text) { String ans = ""; int distractorNumber = 0; int counter = 0; char[] textt = text.ToCharArray(); //while (distractorNumber < 3) //{ while (counter < text.Length) { if (textt[counter] != '~') { ans += textt[counter]; } else { answerChoices[distractorNumber] = ans; ans = ""; distractorNumber++; } counter++; } //} }
/** * Unescapes a String, replacing &#nn;, <, >, &, ", * and &apos to the corresponding characters. * @param s a String with entities * @return the unescaped string */ public static String UnescapeXML(String s) { char[] cc = s.ToCharArray(); int len = cc.Length; StringBuilder sb = new StringBuilder(); int pos; String esc; for (int i = 0; i < len; i++) { int c = cc[i]; if (c == '&') { pos = FindInArray(';', cc, i + 3); if (pos > -1) { esc = new String(cc, i + 1, pos - i - 1); if (esc.StartsWith("#")) { esc = esc.Substring(1); if (IsValidCharacterValue(esc)) { c = (char)int.Parse(esc); i = pos; } else { i = pos; continue; } } else { int tmp = Unescape(esc); if (tmp > 0) { c = tmp; i = pos; } } } } sb.Append((char)c); } return sb.ToString(); }
/// <summary> /// Check if the given string contains only the characters in the /// Chars array being passed. /// </summary> /// <param name="str">The given string object to check.</param> /// <param name="Chars">The array of valid characters that are checked /// in the string.</param> /// <param name="Classic">Switch to force RegEx comparison instead of /// Linq.</param> /// <returns>True if the given string contains only characters in the /// Chars array, else False.</returns> public static bool IsChar(this System.String str, char[] Chars, bool Classic = false) { if (Classic) //No LINQ available e.g. .NET 2.0 { string comparor = @"^["; foreach (char c in Chars) { comparor += c; } comparor += "]+$"; return(System.Text.RegularExpressions.Regex.IsMatch(str, comparor)); } else { foreach (char c in str.ToCharArray()) { if (!Chars.Contains(c)) { return(false); } } return(true); } }
/// <summary> /// Confronta 2 stringhe eliminando caratteri speciali \n /// e restituendo il coefficiente di matching /// </summary> public static double FuzzyCompare(this String str1, String str2) { str1 = str1.Trim().ToLowerInvariant(); str2 = str2.Trim().ToLowerInvariant(); if (String.Compare(str1, str2, true) == 0) return 1.0; char[] chars1 = str1.ToCharArray(); char[] chars2 = str2.ToCharArray(); int pos1 = 0; int pos2 = 0; int length1 = chars1.Length; int length2 = chars2.Length; int matchCount = 0; bool cont = true; while (true) { char c1 = '_', c2 = '/'; length1++; do { length1--; if (pos1 == chars1.Length) { cont = false; break; } c1 = chars1[pos1++]; } while (!((c1 >= 'a' && c1 <= 'z') || (c1 >= '0' && c1 <= '9'))); length2++; do { length2--; if (pos2 == chars2.Length) { cont = false; break; } c2 = chars2[pos2++]; } while (!((c2 >= 'a' && c2 <= 'z') || (c2 >= '0' && c2 <= '9'))); if (!cont) break; if (c1 == c2) { matchCount++; } else { break; } } int maxLength = Math.Max(length1, length2); return matchCount / (double)maxLength; }
// This method converts a hexvalues string as 80FF into a integer. // Note that you may not put a '#' at the beginning of string! There // is not much error checking in this method. If the string does not // represent a valid hexadecimal value it returns 0. public static int HexToInt(String hexstr) { int counter, hexint; char[] hexarr; hexint = 0; hexstr = hexstr.ToUpper(); hexarr = hexstr.ToCharArray(); for (counter = hexarr.Length - 1; counter >= 0; counter--) { if ((hexarr[counter] >= '0') && (hexarr[counter] <= '9')) { hexint += (hexarr[counter] - 48) * ((int)(Math.Pow(16, hexarr.Length - 1 - counter))); } else { if ((hexarr[counter] >= 'A') && (hexarr[counter] <= 'F')) { hexint += (hexarr[counter] - 55) * ((int)(Math.Pow(16, hexarr.Length - 1 - counter))); } else { hexint = 0; break; } } } return hexint; }
/// <summary> It changes the encoding of text file between UTF-8 and the triple encoding.</summary> /// <param name="srcFileName">- the input file /// </param> /// <param name="desFileName">- the output file /// </param> /// <param name="srcEncoding">- the encoding of input file: ENCODING_UNICODE or ENCODING_TRIPLE /// </param> /// <param name="desEncoding">- the encoding of input file: ENCODING_UNICODE or ENCODING_TRIPLE /// </param> /// <throws> IOException </throws> public static void convertFile(System.String srcFileName, System.String desFileName, int srcEncoding, int desEncoding) { System.IO.StreamReader br = new System.IO.StreamReader( new System.IO.FileStream(srcFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read), System.Text.Encoding.UTF8); System.IO.StreamWriter bw = new System.IO.StreamWriter( new System.IO.FileStream(desFileName, System.IO.FileMode.Create), System.Text.Encoding.UTF8); System.String line = null; if (srcEncoding == ENCODING_UNICODE && desEncoding == ENCODING_TRIPLE) { while ((line = br.ReadLine()) != null) { char[] buf = toTripleArray(line); bw.Write(buf); bw.Write('\n'); } } else if (srcEncoding == ENCODING_TRIPLE && desEncoding == ENCODING_UNICODE) { while ((line = br.ReadLine()) != null) { System.String buf = toString(line.ToCharArray()); bw.Write(buf); bw.Write('\n'); } } br.Close(); bw.Close(); }
public static System.String RemoveIllegalChars(System.String Str) { if (Str == null) { Str = "Unknown"; } Str = Str.Replace('\\', '-'); Str = Str.Replace('/', '-'); System.String[] AllowedCharsArray = new System.String[] { "q", "w", "e", "r", "t", "a", "s", "d", "f", "g", "z", "x", "c", "v", "b", "y", "u", "i", "o", "p", "h", "j", "k", "l", "n", "m", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_", " ", "(", ")", "-" }; System.Collections.ArrayList AllowedChars = new System.Collections.ArrayList(AllowedCharsArray); System.String OutStr = ""; foreach (System.Char TestChar in Str.ToCharArray()) { if (AllowedChars.Contains(TestChar.ToString().ToLower())) { OutStr += TestChar.ToString(); } } if (OutStr == "") { OutStr = "Unknown"; } return(OutStr); }
public bool InjectDll(ModuleType process, LPCTSTR szDllPath) { IntPtr pThreadProc; HANDLE hThread, hProcess, pRemoteBuf; SIZE_T bytesWritten = 0; DWORD dwBufSize = (DWORD)(szDllPath.Length + 1) * 2; int buf; //wchar in C UInt16[] wDllPath = szDllPath.ToCharArray().Select(x => (UInt16)x).ToArray(); hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, process.Pid); if (hProcess == IntPtr.Zero) { return(false); } pRemoteBuf = VirtualAllocEx(hProcess, IntPtr.Zero, dwBufSize, MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(hProcess, pRemoteBuf, wDllPath, dwBufSize, ref bytesWritten); pThreadProc = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryW"); unsafe { buf = pRemoteBuf.ToInt32(); } hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, pThreadProc, buf, 0, 0); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); CloseHandle(hProcess); return(true); }
public int StringWidth(String str) { int len = str.Length; char[] data = new char[len]; Array.Copy(str.ToCharArray(), 0, data, 0,len); return CharsWidth(data, 0, len); }
//Convert integer to string, place in char array, reverse char array, convert to string public String reverse(int x) { target = x.ToString(); char[] charArray = target.ToCharArray(); Array.Reverse(charArray); return new string(charArray); }
public static String reverseSentence(String sentence) { char[] reversedSentence = sentence.ToCharArray (); Array.Reverse (reversedSentence); return new string (reversedSentence); }
/// <summary>Parses hex string representing an Ethernet MAC address to the enternal format. Ethernet /// address has to contain 12 hex characters (1-9 or A-F) to be parsed correctly. Special formatting is /// ignored so both 0000.0010.0000 and 00-00-00-10-00-00 will be parsed ok. /// </summary> /// <param name="value">Ethernet address represented as a string. /// </param> public override void Set(System.String value) { if (value == null || value.Length <= 0) { throw new ArgumentException("Invalid argument. String is empty."); } string workString = new string(value.ToCharArray()); for (int cnt = 0; cnt < value.Length; cnt++) { if (!Char.IsNumber(workString[cnt]) && Char.ToUpper(workString[cnt]) != 'A' && Char.ToUpper(workString[cnt]) != 'B' && Char.ToUpper(workString[cnt]) != 'C' && Char.ToUpper(workString[cnt]) != 'D' && Char.ToUpper(workString[cnt]) != 'E' && Char.ToUpper(workString[cnt]) != 'F') { workString.Remove(cnt, 1); cnt -= 1; } } if (workString.Length != 12) { throw new ArgumentException("Invalid Ethernet address format."); } int pos = 0; int bufpos = 0; while (pos + 2 < workString.Length) { string val = workString.Substring(pos, 2); byte v = Byte.Parse(val, NumberStyles.HexNumber); _data[bufpos++] = v; pos += 2; } }
/// <summary>Encodes a String using Base64 (see RFC 1521)</summary> /// <param name="s">string to be encoded</param> /// <example> /// <code> /// string base64EncodedText = MailEncoder.ConvertQP("кгец"); /// </code> /// </example> /// <returns>Base64 encoded string</returns> internal static string ConvertToBase64(String s) { byte[] from = Encoding.ASCII.GetBytes(s.ToCharArray()); string returnMsg = Convert.ToBase64String(from); return returnMsg; }
protected override EnumError AddNewDictItem(String pword, int pCnt) { char[] chars = pword.ToCharArray(); String prefix = ""; foreach (char ch in chars) { prefix += ch; if (dac.ContainsKey(prefix)) { WordItem wi = new WordItem(pword,pCnt); ListOfWordItemSorted lowi = dac[prefix]; lowi.Add(wi, null); //В списке TopN слов всегда храним не более topNWords слов. if (lowi.Count > base.topNWords) { lowi.RemoveAt(base.topNWords); } } else { ListOfWordItemSorted lowi = new ListOfWordItemSorted(); lowi.Capacity = base.topNWords+1; WordItem wi = new WordItem(pword,pCnt); lowi.Add(wi, null); dac.Add(prefix, lowi); } } return EnumError.NoError; }
static int CountSyllablesInWord(String word) { char[] chars = word.ToCharArray(); int syllables = 0; bool lastWasVowel = false; for (int i = 0; i < chars.Length; i++) { char c = chars[i]; if (IsVowel(c)) { if (!lastWasVowel || (i > 0 && IsE(chars, i - 1) && IsO(chars, i))) { ++syllables; lastWasVowel = true; } } else { lastWasVowel = false; } } if (word.EndsWith("oned") || word.EndsWith("ne") || word.EndsWith("ide") || word.EndsWith("ve") || word.EndsWith("fe") || word.EndsWith("nes") || word.EndsWith("mes")) { --syllables; } return syllables; }
public static bool CheckLicense(String LicenseKey) { StringBuilder SB = new StringBuilder(); StringBuilder SB1 = new StringBuilder(); String SerialID = GetSerial(); char[] Chars = SerialID.ToString().ToCharArray(); double R1 = 0; for (int i = 0; i < Chars.Length; i++) { int B = (int)Chars[i]; int E = (int)Chars[Chars.Length - i - 1]; double R = Math.Pow(B * E, 3); R1 = R1 + R * i; SB.Append(R1.ToString()); } String Temp = SB.ToString(); for (int i = 0; i < LicenseKey.Length; i++) { char C = LicenseKey.ToCharArray()[i]; int C1 = Convert.ToInt16(C); if ((C1 >= 48) & (C1 <= 59)) SB1.Append((int)C1 - 48); } if (Temp == SB1.ToString()) return true; else return false; }
public bool DrawClickText(int x, int y, String s, int mosX, int mosY, bool mouseClick) { if (s.Length == 0) return false; int eX = x + GetStringSpace(s.ToCharArray()); bool r = false; if ((mosX > x) && (mosX < eX) && (mosY > y) && (mosY < y + (int)(36.0f * size))) { color = Color.Yellow; if (mouseClick) r = true; } else { color = Color.White; } DrawText(x, y, s); return r; }
/// <summary> /// 过滤特殊字符 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string String2Json(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char c = s.ToCharArray()[i]; switch (c) { case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '/': sb.Append("\\/"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\v': sb.Append("\\v"); break; case '\0': sb.Append("\\0"); break; default: sb.Append(c); break; } } return sb.ToString(); }
public Boolean FindAnagram(String s1, String s2) { if (s1.Length != s2.Length) return false; char[] charS1 = s1.ToCharArray(); char[] charS2 = s2.ToCharArray(); int[] countS1 = new int[numberOfChar];//dictionary 256 int[] countS2 = new int[numberOfChar]; //both string characters should exist in both string with same count for (int i = 0; i < s1.Length ; i++) { countS1[charS1[i]]++; // ascii value as a index countS2[charS2[i]]++; } for (int i = 0; i < numberOfChar; i++) { if(countS1[i]!=countS2[i]) return false; } return true; }
/** * json 只能是类似:{"resultType": "000", "errorCode": "0x0001"}的简单格式。 即,只能有最外层一个{},值的类型全部都是string,不能有内部对象和数组。 * * @param json */ public static Dictionary<String, String> simpleJsonToMap(String json) { var map = new Dictionary<String, String>(); char[] chars = json.ToCharArray(); int a = -1; String key = null; for (var i = 1; i < chars.Length - 1; i++) { if (chars[i] != '\"' || chars[i - 1] == '\\') continue; if (a == -1) { a = i; } else { if (key == null) { key = json.Substring(a + 1, i-a-1); } else { map.Add(key, json.Substring(a + 1, i-a-1).Replace("\\\"", "\"")); key = null; } a = -1; } } return map; }
/// <summary> /// 获取模板中出现的所有变量 /// </summary> /// <param name="template"></param> /// <returns></returns> public static List<String> GetVars( String template ) { List<String> results = new List<String>(); char[] chars = template.ToCharArray(); StringBuilder tempVar = new StringBuilder(); Boolean isVarBegin = false; for (int i = 0; i < chars.Length; i++) { if (i == 0) continue; if (chars[i - 1] == '{' && chars[i] == '*') { tempVar.Remove( 0, tempVar.Length ); isVarBegin = true; continue; } if (chars[i] == '*' && chars[i + 1] == '}') { results.Add( tempVar.ToString() ); isVarBegin = false; continue; } if (isVarBegin) { tempVar.Append( chars[i] ); } } return results; }
public static String RemoveAllNotNumberCharacters(String content) { content = content.Replace(" ", ""); StringBuilder builder = new StringBuilder(); foreach (char character in content.ToCharArray()) { if ((int)character < 48 || (int)character > 57) { builder.Append(" "); } else { builder.Append(character); } } String tempString = builder.ToString(); builder = new StringBuilder(); foreach (String value in tempString.Split(' ')) { if (!String.IsNullOrEmpty(value)) { builder.Append(value).Append(","); } } return builder.ToString().TrimEnd(','); }
protected static String unescapeBackslash(System.String escaped) { if (escaped != null) { int backslash = escaped.IndexOf('\\'); if (backslash >= 0) { int max = escaped.Length; System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 1); unescaped.Append(escaped.ToCharArray(), 0, backslash); bool nextIsEscaped = false; for (int i = backslash; i < max; i++) { char c = escaped[i]; if (nextIsEscaped || c != '\\') { unescaped.Append(c); nextIsEscaped = false; } else { nextIsEscaped = true; } } return(unescaped.ToString()); } } return(escaped); }
private System.Boolean _CheckCharBeforLong(System.String strLine, System.Int32 nIndexOfValue) { System.Boolean bCheckCharBeforLongRes = false; System.String strCharBeforeLong; System.String strAZazString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"; char[] szArrayAZazString = strAZazString.ToCharArray(); System.Int32 nIndex = -1; if (0 == nIndexOfValue) { bCheckCharBeforLongRes = true; return(bCheckCharBeforLongRes); } strCharBeforeLong = m_strLine.Substring(nIndexOfValue - 1, 1); nIndex = strCharBeforeLong.IndexOfAny(szArrayAZazString); if (-1 == nIndex) { bCheckCharBeforLongRes = true; } else { bCheckCharBeforLongRes = false; } return(bCheckCharBeforLongRes); }
private String rot13(String stringToRotate) { Char[] stringAsCharArray = stringToRotate.ToCharArray(); String result = ""; foreach (Char character in stringAsCharArray) { // Get the int value of the character int characterAsciiValue = (int)character; if (characterAsciiValue >= UPPERCASE_A_ASCII_VALUE && characterAsciiValue <= UPPERCASE_Z_ASCII_VALUE) { // Character is a capital letter (A - Z) characterAsciiValue -= UPPERCASE_A_ASCII_VALUE; characterAsciiValue += N_PLACES_TO_ROTATE; characterAsciiValue = characterAsciiValue % N_CHARACTERS_IN_ALPHABET; characterAsciiValue += UPPERCASE_A_ASCII_VALUE; } if (characterAsciiValue >= LOWERCASE_A_ASCII_VALUE && characterAsciiValue <= LOWERCASE_Z_ASCII_VALUE) { // Character is a lowercase letter (a - z) characterAsciiValue -= LOWERCASE_A_ASCII_VALUE; characterAsciiValue += N_PLACES_TO_ROTATE; characterAsciiValue = characterAsciiValue % N_CHARACTERS_IN_ALPHABET; characterAsciiValue += LOWERCASE_A_ASCII_VALUE; } // cast the character ASCII value to a character and add it to result result += (char)characterAsciiValue; } return result; }
private static System.String urlDecode(System.String escaped) { // No we can't use java.net.URLDecoder here. JavaME doesn't have it. if (escaped == null) { return(null); } char[] escapedArray = escaped.ToCharArray(); int first = findFirstEscape(escapedArray); if (first < 0) { return(escaped); } int max = escapedArray.Length; // final length is at most 2 less than original due to at least 1 unescaping System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 2); // Can append everything up to first escape character unescaped.Append(escapedArray, 0, first); for (int i = first; i < max; i++) { char c = escapedArray[i]; if (c == '+') { // + is translated directly into a space unescaped.Append(' '); } else if (c == '%') { // Are there even two more chars? if not we will just copy the escaped sequence and be done if (i >= max - 2) { unescaped.Append('%'); // append that % and move on } else { int firstDigitValue = parseHexDigit(escapedArray[++i]); int secondDigitValue = parseHexDigit(escapedArray[++i]); if (firstDigitValue < 0 || secondDigitValue < 0) { // bad digit, just move on unescaped.Append('%'); unescaped.Append(escapedArray[i - 1]); unescaped.Append(escapedArray[i]); } unescaped.Append((char)((firstDigitValue << 4) + secondDigitValue)); } } else { unescaped.Append(c); } } return(unescaped.ToString()); }
/// <summary> Make a C#-ish accessor method name out of a field or component description /// by removing non-letters and adding "get". One complication is that some description /// entries in the DB have their data types in brackets, and these should not be /// part of the method name. On the other hand, sometimes critical distinguishing /// information is in brackets, so we can't omit everything in brackets. The approach /// taken here is to eliminate bracketed text if a it looks like a data type. /// </summary> public static System.String makeAccessorNameCSharp(System.String fieldDesc, int repitions) { System.Text.StringBuilder aName = new System.Text.StringBuilder(); if (repitions != 1) { aName.Append("get"); } char[] chars = fieldDesc.ToCharArray(); bool lastCharWasNotLetter = true; int inBrackets = 0; System.Text.StringBuilder bracketContents = new System.Text.StringBuilder(); for (int i = 0; i < chars.Length; i++) { if (chars[i] == '(') { inBrackets++; } if (chars[i] == ')') { inBrackets--; } if (System.Char.IsLetterOrDigit(chars[i])) { if (inBrackets > 0) { //buffer everthing in brackets bracketContents.Append(chars[i]); } else { //add capitalized bracketed text if appropriate if (bracketContents.Length > 0) { aName.Append(capitalize(filterBracketedText(bracketContents.ToString()))); bracketContents = new System.Text.StringBuilder(); } if (lastCharWasNotLetter) { //first letter of each word is upper-case aName.Append(System.Char.ToUpper(chars[i])); } else { aName.Append(chars[i]); } lastCharWasNotLetter = false; } } else { lastCharWasNotLetter = true; } } aName.Append(capitalize(filterBracketedText(bracketContents.ToString()))); return(aName.ToString()); }
IntSliderControl m_Offset = 0; // [0,1024] Offset #endregion void Render(Surface dst, Surface src, Rectangle rect) { if (m_Text.Length <= 0) { return; } var charArray = m_Text.ToCharArray(); var charIndex = 0; var pixelIndex = m_Offset; ColorBgra CurrentPixel; for (int y = rect.Top; y < rect.Bottom; y++) { if (IsCancelRequested) { return; } for (int x = rect.Left; x < rect.Right; x++) { CurrentPixel = src[x, y]; if (charIndex < charArray.Length && pixelIndex % m_Modulus == 0) { byte r = CurrentPixel.R; byte b = CurrentPixel.B; byte currentChar = (byte)charArray[charIndex]; if (charIndex % 2 == 0) { byte currentChar01 = (byte)(currentChar & 0b00000011); byte currentChar23 = (byte)(currentChar & 0b00001100); r = (byte)((r & ~0b00000011) | currentChar01); b = (byte)((b & ~0b00001100) | currentChar23); } else { byte currentChar45 = (byte)(currentChar & 0b00110000); byte currentChar67 = (byte)(currentChar & 0b11000000); r = (byte)((r & ~0b00110000) | currentChar45); b = (byte)((b & ~0b11000000) | currentChar67); } CurrentPixel.R = r; CurrentPixel.B = b; ++charIndex; } dst[x, y] = CurrentPixel; ++pixelIndex; } } }
/// <summary> Stem a word provided as a String. Returns the result as a String.</summary> public virtual System.String Stem(System.String s) { if (Stem(s.ToCharArray(), s.Length)) { return ToString(); } else return s; }
/// <summary> It recognizes informal sentences in which an eojeol is quite long and some characters were /// repeated many times. To prevent decrease of analysis performance because of those unimportant /// irregular pattern, it inserts some blanks in those eojeols to seperate them. /// </summary> public virtual PlainSentence doProcess(PlainSentence ps) { System.String word = null; System.Text.StringBuilder buf = new System.Text.StringBuilder(); StringTokenizer st = new StringTokenizer(ps.Sentence, " \t"); while (st.HasMoreTokens) { word = st.NextToken; /* repeated character */ if (word.Length > REPEAT_CHAR_ALLOWED) { char[] wordArray = word.ToCharArray(); int repeatCnt = 0; char checkChar = wordArray[0]; buf.Append(checkChar); for (int i = 1; i < wordArray.Length; i++) { if (checkChar == wordArray[i]) { if (repeatCnt == REPEAT_CHAR_ALLOWED - 1) { buf.Append(' '); buf.Append(wordArray[i]); repeatCnt = 0; } else { buf.Append(wordArray[i]); repeatCnt++; } } else { if (checkChar == '.') { buf.Append(' '); } buf.Append(wordArray[i]); checkChar = wordArray[i]; repeatCnt = 0; } } } else { buf.Append(word); } buf.Append(' '); } ps.Sentence = buf.ToString(); return(ps); }
public override System.Object init(InternalContextAdapter context, System.Object data) { Token t = FirstToken; System.String text = NodeUtils.tokenLiteral(t); ctext = text.ToCharArray(); return(data); }
/// <summary> /// Returns the binary representation of a given string object. /// </summary> /// <param name="str">The System.String object to convert to binary.</param> /// <returns></returns> public static string ToBinary(this System.String str) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (byte b in System.Text.ASCIIEncoding.UTF8.GetBytes( str.ToCharArray())) { sb.Append(Convert.ToString(b, 2) + " "); } return(sb.ToString()); }
public static void writeFile(System.String str, System.String filename, bool append) { int length = str.Length; //UPGRADE_TODO: Class 'java.io.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriter'" //UPGRADE_TODO: Constructor 'java.io.FileWriter.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriterFileWriter_javalangString_boolean'" System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(filename, append, System.Text.Encoding.Default); out_Renamed.Write(str.ToCharArray(), 0, length); out_Renamed.Close(); }
/// <summary> writes a single frame in XYZ format to the Writer.</summary> /// <param name="mol">the Molecule to write /// </param> public virtual void writeMolecule(IMolecule mol) { System.String st = ""; bool writecharge = true; try { System.String s1 = ((System.Int32)mol.AtomCount).ToString(); //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" writer.Write(s1.ToCharArray(), 0, s1.Length); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); System.String s2 = null; // FIXME: add some interesting comment if (s2 != null) { //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" writer.Write(s2.ToCharArray(), 0, s2.Length); } //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); // Loop through the atoms and write them out: IAtom[] atoms = mol.Atoms; for (int i = 0; i < atoms.Length; i++) { IAtom a = atoms[i]; st = a.Symbol; Point3d p3 = a.getPoint3d(); if (p3 != null) { st = st + "\t" + p3.x.ToString() + "\t" + p3.y.ToString() + "\t" + p3.z.ToString(); } if (writecharge) { double ct = a.getCharge(); st = st + "\t" + ct; } //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" writer.Write(st.ToCharArray(), 0, st.Length); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } catch (System.IO.IOException e) { // throw e; //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.error("Error while writing file: ", e.Message); //logger.debug(e); } }
/// <summary> /// Validates that the given string object contains all numeric /// characters(0-9) returning True if it does and False if it /// doesn't. /// </summary> /// <param name="str">The given string object to check.</param> /// <param name="Classic">Switch to force RegEx comparison instead of Linq.</param> /// <returns>True if all characters in the given string are numeric, else False.</returns> public static bool IsNumeric(this System.String str, bool Classic = false) { if (Classic) //No LINQ available e.g. .NET 2.0 { return(System.Text.RegularExpressions.Regex.IsMatch(str, @"^[0-9]+$")); } else //This method is on average 670% faster than the Classic RegEx method. { return(str.ToCharArray().All(Char.IsDigit)); } }
public static long ToLong(System.String t) { long ival = 0; char[] tb = t.ToCharArray(); for (int i = 0; i < tb.Length; i++) { ival += powersOf36[i] * digits.IndexOf(tb[tb.Length - i - 1]); } return(ival); }
public MODTYPE(System.String init_id, int init_chn, System.String init_name) { id = new sbyte[5]; byte[] tmp; //SupportClass.GetSBytesFromString(init_id, 0, 4, ref id, 0); tmp = System.Text.UTF8Encoding.UTF8.GetBytes(init_id); Buffer.BlockCopy(tmp, 0, id, 0, 4); id[4] = 0; //'\x0000'; channels = (short)init_chn; name = new System.String(init_name.ToCharArray()); }
/// <summary> Convert a string, returning the new string. /// /// </summary> /// <param name="text">the string to convert /// </param> /// <returns> the converted string /// @throws FlexCelException if the string cannot be converted according to the options. /// @stable ICU 2.0 /// </returns> public System.String shape(System.String text) { char[] src = text.ToCharArray(); char[] dest = src; if (((options & LENGTH_MASK) == LENGTH_GROW_SHRINK) && ((options & LETTERS_MASK) == LETTERS_UNSHAPE)) { dest = new char[src.Length * 2]; // max } int len = shape(src, 0, src.Length, dest, 0, dest.Length); return(new System.String(dest, 0, len)); }
/* * Write a string to the stream. * * @param s the string to write. **/ public virtual void write_string(System.String s) { int len = s.Length; switch (len) { case 0: this.write_nil(); break; default: //UPGRADE_NOTE: This code will be optimized in the future; byte[] tmpBytes; int i; string tmpStr; tmpStr = s; tmpBytes = new byte[tmpStr.Length]; i = 0; while (i < tmpStr.Length) { tmpBytes[i] = (byte)tmpStr[i]; i++; } byte[] bytebuf = tmpBytes; /*switch to se if the length of * the byte array is equal to the * length of the list */ if (bytebuf.Length == len) { /*Usual */ this.write1(OtpExternal.stringTag); this.write2BE(len); this.writeN(bytebuf); } else { /*Unicode */ char[] charbuf = s.ToCharArray(); this.write_list_head(len); for (int i2 = 0; i2 < len; i2++) { this.write_char(charbuf[i2]); } this.write_nil(); } break; } }
static StackObject *ToCharArray_27(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String instance_of_this_method = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.ToCharArray(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public void test() { char[] chars = "hello".ToCharArray(); string myString = new System.String(chars); for (int i = 0; i < myString.Length; i++) { char ch = myString.ToCharArray()[i]; } // * Inheritance IComparable myComparable = myString; Object myObject = myString; String otherOne = myString; }
/// <summary> /// Returns the next token from the source string, using the provided /// token delimiters /// </summary> /// <param name="delimiters">String containing the delimiters to use</param> /// <returns>The string value of the token</returns> public System.String NextToken(System.String delimiters) { //According to documentation, the usage of the received delimiters should be temporary (only for this call). //However, it seems it is not true, so the following line is necessary. this._delimiters = delimiters; //at the end if (this._currentPos == this._chars.Length) { throw new System.ArgumentOutOfRangeException(); } //if over a delimiter and delimiters must be returned else if ((System.Array.IndexOf(delimiters.ToCharArray(), _chars[this._currentPos]) != -1) && this._includeDelims) { return("" + this._chars[this._currentPos++]); } //need to get the token wo delimiters. else { return(nextToken(delimiters.ToCharArray())); } }
/// <summary> Replaces the character at the specified position of the string str1 /// with the first character of the string str2. /// </summary> /// <param name="str1">- base string /// </param> /// <param name="cur">- index of the character to /// </param> /// <param name="str2">- the first character of the string is used to replace /// </param> /// <returns> the string with the new character replaced /// </returns> private System.String replace(System.String str1, int cur, System.String str2) { char[] array = str1.ToCharArray(); if (str2.Length == 0) { System.Console.Error.WriteLine("Exp.java: replace(): s is to short"); System.Environment.Exit(0); } array[cur] = str2[0]; return(new string(array)); }
public void testWrong() { string myString = new System.String(3); // * Error for (int i = 0; i < myString.Length; i++) { char ch = myString.ToCharArray(); // * Error } // * Inheritance MyString myType = myString; // * Error object o; myString = o; // * Error }
public virtual void TestModifyOnUnmodifiable() { //System.Diagnostics.Debugger.Break(); CharArraySet set = new CharArraySet(10, true); set.AddAll(TEST_STOP_WORDS); int size = set.Count; set = CharArraySet.UnmodifiableSet(set); Assert.AreEqual(size, set.Count, "Set size changed due to UnmodifiableSet call"); System.String NOT_IN_SET = "SirGallahad"; Assert.IsFalse(set.Contains(NOT_IN_SET), "Test String already exists in set"); Assert.Throws <NotSupportedException>(() => set.Add(NOT_IN_SET.ToCharArray()), "Modified unmodifiable set"); Assert.IsFalse(set.Contains(NOT_IN_SET), "Test String has been added to unmodifiable set"); Assert.AreEqual(size, set.Count, "Size of unmodifiable set has changed"); Assert.Throws <NotSupportedException>(() => set.Add(NOT_IN_SET), "Modified unmodifiable set"); Assert.IsFalse(set.Contains(NOT_IN_SET), "Test String has been added to unmodifiable set"); Assert.AreEqual(size, set.Count, "Size of unmodifiable set has changed"); Assert.Throws <NotSupportedException>(() => set.Add(new System.Text.StringBuilder(NOT_IN_SET)), "Modified unmodifiable set"); Assert.IsFalse(set.Contains(NOT_IN_SET), "Test String has been added to unmodifiable set"); Assert.AreEqual(size, set.Count, "Size of unmodifiable set has changed"); Assert.Throws <NotSupportedException>(() => set.Clear(), "Modified unmodifiable set"); Assert.IsFalse(set.Contains(NOT_IN_SET), "Changed unmodifiable set"); Assert.AreEqual(size, set.Count, "Size of unmodifiable set has changed"); Assert.Throws <NotSupportedException>(() => set.Add((object)NOT_IN_SET), "Modified unmodifiable set"); Assert.IsFalse(set.Contains(NOT_IN_SET), "Test String has been added to unmodifiable set"); Assert.AreEqual(size, set.Count, "Size of unmodifiable set has changed"); Assert.Throws <NotSupportedException>(() => set.RemoveAll(new List <string>(TEST_STOP_WORDS)), "Modified unmodifiable set"); Assert.AreEqual(size, set.Count, "Size of unmodifiable set has changed"); Assert.Throws <NotSupportedException>(() => set.RetainAll(new List <string>(new[] { NOT_IN_SET })), "Modified unmodifiable set"); Assert.AreEqual(size, set.Count, "Size of unmodifiable set has changed"); Assert.Throws <NotSupportedException>(() => set.AddAll(new List <string>(new[] { NOT_IN_SET })), "Modified unmodifiable set"); Assert.IsFalse(set.Contains(NOT_IN_SET), "Test String has been added to unmodifiable set"); for (int i = 0; i < TEST_STOP_WORDS.Length; i++) { Assert.IsTrue(set.Contains(TEST_STOP_WORDS[i])); } }
/// <summary> Removes leading whitespace. /// /// </summary> /// <seealso cref="ca.uhn.hl7v2.validation.PrimitiveTypeRule.correct(java.lang.String)"> /// </seealso> public virtual System.String correct(System.String value_Renamed) { System.String trmValue = null; if (value_Renamed != null) { char[] stringChr = value_Renamed.ToCharArray(); for (int i = 0; i < stringChr.Length && trmValue == null; i++) { if (!System.Char.IsWhiteSpace(stringChr[i])) { trmValue = new System.String(stringChr, i, (stringChr.Length - i)); } } } return(trmValue); }
// // Summary: // Reads the next character from the input stream and advances the character // position by one character. // // Returns: // The next character from the input stream, or -1 if no more characters are // available. The default implementation returns -1. // // Exceptions: // System.IO.IOException: // An I/O error occurs. // // System.ObjectDisposedException: // The System.IO.TextReader is closed. public override int Read() { needsChars = true; int av = myBuffer.Length; while (av < 1) { lispEngine.Yield(); av = myBuffer.Length; // Monitor.Wait(lispEngine); } char c = myBuffer.ToCharArray()[0]; Consume(1); needsChars = false; return(c); }
/// <summary> It expands the morpheme chart to deal with the phoneme change phenomenon.</summary> /// <param name="from">- the index of the start segment position /// </param> /// <param name="front">- the front part of the string /// </param> /// <param name="back">- the next part of the string /// </param> /// <param name="ftag">- the morpheme tag of the front part /// </param> /// <param name="btag">- the morpheme tag of the next part /// </param> /// <param name="phoneme">- phoneme /// </param> public virtual void phonemeChange(int from, System.String front, System.String back, int ftag, int btag, int phoneme) { TNODE node = null; int size = 0; bool x, y; int next; int nc_idx; // searches the system dictionary for the front part node = systemDic.fetch(front.ToCharArray()); if (node != null && node.info_list != null) { size = node.info_list.Count; } Position pos = sp.getPosition(from); for (int i = 0; i < size; i++) { INFO info = node.info_list.Get_Renamed(i); // comparison of the morpheme tag of the front part x = tagSet.checkTagType(ftag, info.tag); // comparison of the phoneme of the front part y = tagSet.checkPhonemeType(phoneme, info.phoneme); if (x && y) { next = altSegment(back); if (checkChart(pos.morpheme, pos.morphCount, info.tag, info.phoneme, next, btag, front) == false) { nc_idx = addMorpheme(info.tag, info.phoneme, next, btag); chart[nc_idx].str = front; pos.morpheme[pos.morphCount++] = nc_idx; } else { System.Console.Error.WriteLine("phonemeChange: exit"); System.Environment.Exit(0); } } } }
/// <summary> /// 过滤特殊字符 /// </summary> /// <param name="s"></param> /// <returns></returns> private static string String2Json(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char c = s.ToCharArray()[i]; switch (c) { case '\"': sb.Append("\\\""); break; case '\\': sb.Append("////"); break; case '/': sb.Append("///"); break; case '\b': sb.Append("//b"); break; case '\f': sb.Append("//f"); break; case '\n': sb.Append("//n"); break; case '\r': sb.Append("//r"); break; case '\t': sb.Append("//t"); break; default: sb.Append(c); break; } } return sb.ToString(); }