game-xna-intro-XnaShooterUIProject-Helpers-StringHelper.cs / cs
// Project: XnaGraphicEngine, File: StringHelper.cs // Namespace: XnaGraphicEngine.Helpers, Class: StringHelper // Creation date: 22.11.2004 09:51 // Last modified: 19.01.2006 04:10 // Generated with Commenter by abi.exDream.com #region Using directives if DEBUG //using NUnit.Framework; endif using System; using System.Text; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Diagnostics; using System.Collections.Generic; #endregion namespace XnaGraphicEngine.Helpers {
#region Constructor (it is not allowed to instantiate)
#region Comparing, Counting and Extraction
foreach (string match in anyMatch) if (String.Compare(s1, match, true, CultureInfo.CurrentCulture) == 0) return true; return false; } // Compare(s1, anyMatch)
foreach (string listEntry in list) if (String.Compare(name, listEntry, ignoreCase, CultureInfo.CurrentCulture) == 0) return true; return false; } // IsInList(name, list, ignoreCase)
foreach (string listEntry in list) if (String.Compare(name, listEntry, ignoreCase, CultureInfo.CurrentCulture) == 0) return true; return false; } // IsInList(name, list, ignoreCase)
return text.Split(new char[] { ' ' }).Length; } // CountWords(text)
string[] words = text.Split(new char[] { ' ' }); if (words.Length > 0) return words[words.Length - 1]; return text; } // GetLastWord(text)
StringBuilder ret = new StringBuilder(); for (int pos = 0; pos < text.Length; pos++) { if (text[pos] == ' ' || text[pos] == '\t') ret.Append(text[pos]); else break; } // for (pos) return ret.ToString(); } // GetAllSpacesAndTabsAtBeginning(text)
string[] splitted = originalText.Split(new char[] { ' ' }); string ret = ""; foreach (string word in splitted) { if (word.Length <= maxLength) ret += word + " "; else { for (int i = 0; i < word.Length / maxLength; i++) ret += word.Substring(i * maxLength, maxLength) + " "; } // else } // foreach (word, splitted) return ret.TrimEnd(); } // CheckStringWordLength(originalText, maxLength) #endregion #region String contains (for case insensitive compares)
#region Write data
if !XBOX360
// Msg is already that long or longer? if (message.Length >= spaces) return message; // Create string with number of specified spaces char[] ret = new char[spaces]; // Copy data int i; for (i = 0; i < message.Length; i++) ret[i] = message[i]; // Fill rest with spaces for (i = message.Length; i < spaces; i++) ret[i] = ' '; // Return result return new string(ret); } // WriteIntoSpaceString(message, spaces)
#region Convert methods
string[] splitted = s.Split(new char[] { ' ' }); int[] ret = new int[splitted.Length]; for (int i = 0; i < ret.Length; i++) { try { ret[i] = Convert.ToInt32(splitted[i]); } // try catch { } // ignore } // for (i) return ret; } // ConvertStringToIntArray(str)
string[] splitted = s.Split(new char[] { ' ' }); float[] ret = new float[splitted.Length]; for (int i = 0; i < ret.Length; i++) { try { ret[i] = Convert.ToSingle(splitted[i], CultureInfo.InvariantCulture); } // try catch { } // ignore } // for (i) return ret; } // ConvertStringToIntArray(str) #endregion #region File stuff
// Update 2006-09-29: also checking for normal slashes, needed // for support reading 3ds max stuff. string[] fileName = pathFile.Split(new char[] { '\\', '/' }); if (fileName.Length == 0) { if (cutExtension) return CutExtension(pathFile); return pathFile; } // if (fileName.Length) if (cutExtension) return CutExtension(fileName[fileName.Length - 1]); return fileName[fileName.Length - 1]; } // ExtractFilename(pathFile, cutExtension)
return (string[])localList.ToArray(typeof(string)); } // SplitDirectories(path)
#region String splitting and getting it back together
ArrayList ret = new ArrayList(); // Supports any format, only \r, only \n, normal \n\r, // crazy \r\n or even mixed \n\r with any format string[] splitted1 = text.Split(new char[] { '\n' }); string[] splitted2 = text.Split(new char[] { '\r' }); string[] splitted = splitted1.Length >= splitted2.Length ? splitted1 : splitted2; foreach (string s in splitted) { // Never add any \r or \n to the single lines if (s.EndsWith("\r") || s.EndsWith("\n")) ret.Add(s.Substring(0, s.Length - 1)); else if (s.StartsWith("\n") || s.StartsWith("\r")) ret.Add(s.Substring(1)); else ret.Add(s); } // foreach (s, splitted) return (string[])ret.ToArray(typeof(string)); } // SplitMultiLineText(text)
// Check if all values are in range (correct if not) if (startLine >= lines.Length) startLine = lines.Length - 1; if (endLine >= lines.Length) endLine = lines.Length - 1; if (startLine < 0) startLine = 0; if (endLine < 0) endLine = 0; if (startOffset >= lines[startLine].Length) startOffset = lines[startLine].Length - 1; if (endOffset >= lines[endLine].Length) endOffset = lines[endLine].Length - 1; if (startOffset < 0) startOffset = 0; if (endOffset < 0) endOffset = 0; StringBuilder builder = new StringBuilder((endLine - startLine) * 80); for (int lineNumber = startLine; lineNumber <= endLine; lineNumber++) { if (lineNumber == startLine) builder.Append(lines[lineNumber].Substring(startOffset)); else if (lineNumber == endLine) builder.Append(lines[lineNumber].Substring(0, endOffset + 1)); else builder.Append(lines[lineNumber]); if (lineNumber != endLine) builder.Append(separator); } // for (lineNumber) return builder.ToString(); } // BuildStringFromLines(lines, startLine, startOffset) static public string BuildStringFromLines( string[] lines, string separator) { StringBuilder builder = new StringBuilder(lines.Length * 80); for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++) { builder.Append(lines[lineNumber]); if (lineNumber != lines.Length - 1) builder.Append(separator); } // for (lineNumber) return builder.ToString(); } // BuildStringFromLines(lines, separator)
StringBuilder builder = new StringBuilder((endLine - startLine) * 80); for (int lineNumber = startLine; lineNumber <= endLine; lineNumber++) { builder.Append(lines[lineNumber]); if (lineNumber != endLine) builder.Append(separator); } // for (lineNumber) return builder.ToString(); } // BuildStringFromLines(lines, startLine, endLine)
if (cutMode == CutMode.Begin) return originalText.Substring( originalText.Length - maxLength, maxLength); else if (cutMode == CutMode.End) return originalText.Substring(0, maxLength); else // logic: if ( cutMode == CutModes.BothEnds ) return originalText.Substring( (originalText.Length - maxLength) / 2, maxLength); } // MaxStringLength(originalText, maxLength, cutMode)
int index = sourceText.IndexOf(ch); if (index == -1) return sourceText; return sourceText.Substring(0, index); } // GetLeftPartAtFirstOccurence(sourceText, ch)
int index = sourceText.IndexOf(ch); if (index == -1) return ""; return sourceText.Substring(index + 1); } // GetRightPartAtFirstOccurrence(sourceText, ch)
int index = sourceText.LastIndexOf(ch); if (index == -1) return sourceText; return sourceText.Substring(0, index); } // GetLeftPartAtLastOccurrence(sourceText, ch)
int index = sourceText.LastIndexOf(ch); if (index == -1) return sourceText; return sourceText.Substring(index + 1); } // GetRightPartAtLastOccurrence(sourceText, ch)
string passwordString = ""; for (int i = 0; i < originalText.Length; i++) passwordString += "*"; return passwordString; } // CreatePasswordString(originalText)
// Abbreviation has to be at least 2 letters long. if (abbreviation.Length >= 2) { // If not at end of functionName, last letter belongs to next name, // e.g. "TW" is not a abbreviation in "HiMrTWhatsUp", // "AB" isn't one either in "IsABall", // but "PQ" is in "PQList" and "AB" is in "MyAB" if (startPos + abbreviation.Length >= functionName.Length) // Ok, then return full abbreviation length return abbreviation.Length; // Else return length - 1 because of next word return abbreviation.Length - 1; } // if (abbreviation.Length) // No Abbreviation, just return 1 return 1; } // GetAbbreviationLengthInFunctionName(functionName, startPos)
string ret = ""; // Go through functionName and find big letters! for (int pos = 0; pos < functionName.Length; pos++) { char letter = functionName[pos]; // First letter is always big! if (pos == 0 || pos == 1 && StringHelper.IsUppercaseLetter(functionName[1]) && StringHelper.IsUppercaseLetter(functionName[0]) || pos == 2 && StringHelper.IsUppercaseLetter(functionName[2]) && StringHelper.IsUppercaseLetter(functionName[1]) && StringHelper.IsUppercaseLetter(functionName[0])) ret += StringHelper.ToUpper(letter); // Found uppercase letter? else if (StringHelper.IsUppercaseLetter(letter) && //also support numbers and other symbols not lower/upper letter: //StringHelper.IsLowercaseLetter(letter) == false && // But don't allow space or any punctuation (. , : ; ' " ! ?) StringHelper.IsSpaceOrPunctuation(letter) == false && ret.EndsWith(" ") == false) { // Could be new word, but we have to check if its an abbreviation int abbreviationLength = GetAbbreviationLengthInFunctionName( functionName, pos); // Found valid abbreviation? if (abbreviationLength > 1) { // Then add it ret += " " + functionName.Substring(pos, abbreviationLength); // And advance pos (abbreviation is longer than 1 letter) pos += abbreviationLength - 1; } // if (abbreviationLength) // Else just add new word (in lower letter) else ret += " " + StringHelper.ToLower(letter); } // else if else // Just add letter ret += letter; } // for (pos) return ret; } // SplitFunctionNameToWordString(functionName) #endregion #region Remove character
if (text.Contains(characterToBeRemoved.ToString())) text = text.Replace(characterToBeRemoved.ToString(), ""); } // RemoveCharacter(text, characterToBeRemoved) #endregion #region Kb/mb name generator
if (bigByteNumber <= 999) return bigByteNumber + " Bytes"; if (bigByteNumber <= 999 * 1024) { double fKB = (double)bigByteNumber / 1024.0; return (int)fKB + decimalSeperator + ((int)(fKB * 100.0f) % 100).ToString("00") + " KB"; } // if if (bigByteNumber <= 999 * 1024 * 1024) { double fMB = (double)bigByteNumber / (1024.0 * 1024.0); return (int)fMB + decimalSeperator + ((int)(fMB * 100.0f) % 100).ToString("00") + " MB"; } // if // this is very big ^^ will not fit into int if (bigByteNumber <= 999L * 1024L * 1024L * 1024L) { double fGB = (double)bigByteNumber / (1024.0 * 1024.0 * 1024.0); return (int)fGB + decimalSeperator + ((int)(fGB * 100.0f) % 100).ToString("00") + " GB"; } // if //if ( num <= 999*1024*1024*1024*1024 ) //{ double fTB = (double)bigByteNumber / (1024.0 * 1024.0 * 1024.0 * 1024.0); return (int)fTB + decimalSeperator + ((int)(fTB * 100.0f) % 100).ToString("00") + " TB"; //} // if } // WriteBigByteNumber(num, decimalSeperator)
#region Try parse methods that are not available on the XBox360!
// has float group seperators ? if (numberFormat.CurrencyGroupSeparator.IndexOf(strInChars[i]) == 0) { hasGroupSeperator = true; } // if (numberFormat.CurrencyGroupSeparator.IndexOf) } // for (int) if (hasGroupSeperator) { // If first digit is the group seperator or begins with 0, // there is something wrong, the group seperator is used as a comma. if (str.StartsWith(numberFormat.CurrencyGroupSeparator) || strInChars[0] == '0') return false; // look only at the digits in front of the decimal point string[] splittedByDecimalSeperator = str.Split( numberFormat.CurrencyDecimalSeparator.ToCharArray()); #region Invert the digits for modulo check // ==> 1.000 -> 000.1 ==> only after 3 digits char[] firstSplittedInChars = splittedByDecimalSeperator[0].ToCharArray(); int arrayLength = firstSplittedInChars.Length; char[] firstSplittedInCharsInverted = new char[arrayLength]; for (int i = 0; i < arrayLength; i++) { firstSplittedInCharsInverted[i] = firstSplittedInChars[arrayLength - 1 - i]; } // for (int) #endregion // group seperators are only allowed between 3 digits -> 1.000.000 for (int i = 0; i < arrayLength; i++) { if (i % 3 != 0 && numberFormat.CurrencyGroupSeparator.IndexOf( firstSplittedInCharsInverted[i]) == 0) { return false; } // if (i) } // for (int) } // if (hasGroupSeperator) if (decimalSeperatorCount > 1) return false; return true; } // AllowOnlyOneDecimalPoint(str, numberFormat)
//not supported by Convert.ToSingle: //if (str.EndsWith("f")) // str = str.Substring(0, str.Length - 1); // Only 1 decimal point is allowed if (AllowOnlyOneDecimalPoint(str, numberFormat) == false) return false; // + allows in the first,last,don't allow in middle of the string // - allows in the first,last,don't allow in middle of the string // // , allows in the last,middle,don't allow in first char of the string // . allows in the first,last,middle, allows in all the indexs bool retVal = false; // If string is just 1 letter, don't allow it to be a sign if (str.Length == 1 && "+-.,".IndexOf(str[0]) >= 0) return false; for (int i = 0; i < str.Length; i++) { // For first indexchar char pChar = //char.Parse(str.Substring(i, 1)); Convert.ToChar(str.Substring(i, 1)); if (retVal) retVal = false; if ((!retVal) && (str.IndexOf(pChar) == 0)) { retVal = ("+-// if () // For middle characters if ((!retVal) && (str.IndexOf(pChar) > 0) && (str.IndexOf(pChar) < (str.Length - 1))) { retVal = (",.0123456789".IndexOf(pChar) >= 0) ? true : false; } // if () // For last characters if ((!retVal) && (str.IndexOf(pChar) == (str.Length - 1))) { retVal = ("+-,.0123456789".IndexOf(pChar) >= 0) ? true : false; } // if () if (!retVal) break; } // for (int) return retVal; } // IsNumericFloat(str, numberFormat)
// Go through every letter in str int strPos = 0; foreach (char ch in str) { // Only 0-9 are allowed if ("0123456789".IndexOf(ch) < 0 && // Allow +/- for first char (strPos > 0 || (ch != '-' && ch != '+'))) return false; strPos++; } // foreach (ch in str) // All fine, return true, this is a number! return true; } // IsNumericInt(str) #endregion #region Unit Testing if DEBUG /*include NUnit.Framework for this
namespace TestVs2003 { public class Form1 : System.Windows.Forms.Form {
// Also test other functions string[] words = SplitAndTrim(testText, ' '); Assert.AreEqual(words.Length, CountWords(testText), "words.Length"); Assert.AreEqual(testText, BuildStringFromLines(words, " ")); // Call with some invalid values BuildStringFromLines(words, 1, -3, 4, 6, " "); BuildStringFromLines(words, 1, 3, 400, 6, " "); BuildStringFromLines(words, 1, 3, 4, 600, " "); // Check is we can build a part back together // Check if we can build a part back together Assert.AreEqual( testText.Substring(10, 20), BuildStringFromLines(lines, 0, 10, 2, 12, NewLine)); // Get section code and check if we got everything right Assert.AreEqual( @"static void Main() { Application.Run(new Form1()); }", BuildStringFromLines(lines, 10, 2, 13, 3, NewLine)); // Also check if we change some line we still got the same // number of resulting lines. lines[13] += " // Test comment"; Assert.AreEqual(lines.Length, SplitMultilineText(BuildStringFromLines(lines, NewLine)).Length); } // TestSplitStringAndCombineAgain()
thats it").Length); // Test few empty lines Assert.AreEqual(6, StringHelper.SplitMultilineText( "hi\n\n\n\n\rthere\n").Length); // Test all combination of '\r' and '\n' Assert.AreEqual(2, StringHelper.SplitMultilineText( "test1" + '\r' + "test2").Length); Assert.AreEqual(2, StringHelper.SplitMultilineText( "test1" + '\n' + "test2").Length); Assert.AreEqual(2, StringHelper.SplitMultilineText( "test1" + "\n\r" + "test2").Length); Assert.AreEqual(2, StringHelper.SplitMultilineText( "test1" + "\r\n" + "test2").Length); // Also test if mixing normal "\n\r" with '\r' or '\n' Assert.AreEqual(3, StringHelper.SplitMultilineText( "test1" + '\n' + "" + '\r' + "test2" + '\r' + "test3").Length); Assert.AreEqual(3, StringHelper.SplitMultilineText( "test1" + '\n' + "" + '\r' + "test2" + '\n' + "test3").Length); } // TestSplitMultilineText()
// Test with text that already got spaces (we expect same stuff // returned) Assert.AreEqual( "Ha ha, I have spaces already", SplitFunctionNameToWordString("ha ha, I have spaces already")); // Test mixed text Assert.AreEqual( "Hey what means What the hell?", SplitFunctionNameToWordString("Hey what means WhatTheHell?")); // Test some crazy strings to test if we get no exceptions SplitFunctionNameToWordString("\0\t\n\raoeu\b\t"); SplitFunctionNameToWordString("@#%#@G SINDTBRPI\"'45453'"); } // TestSplitFunctionNameToWordString() #region Test get extension
endif #endregion } // class StringHelper } // namespace XnaGraphicEngine.Helpers
(C) Æliens 20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.