Insert() public method

public Insert ( int index, bool value ) : StringBuilder
index int
value bool
return StringBuilder
Beispiel #1
0
        static String GetDirectoryPath(XmlNode componentNode, XmlNamespaceManager nsm)
        {
            XmlNode parent = componentNode.ParentNode;
            StringBuilder installationPath = new StringBuilder("");

            if (parent != null)
            {
                XmlAttribute id = parent.Attributes["Id"];
                string s_id = (id != null) ? id.Value : "";

                // If it is of type wix:Directory get the name or id.
                if (parent.Name == "Directory")
                {
                    installationPath.Insert(0, GetNodeDirectory(parent, nsm));
                    installationPath.Insert(0, GetDirectoryPath(parent, nsm));
                }
                // If the parent is of type wix:DirectoryRef find the wix:Directory node that the
                // DirectoryRef points to and then get the name or id.
                else if (parent.Name == "DirectoryRef")
                {
                    if (!String.IsNullOrEmpty(s_id))
                    {
                        XmlNode installdir = parent.SelectSingleNode(String.Format("//wix:Directory[@Id='{0}']", s_id), nsm);
                        if (installdir != null)
                        {
                            installationPath.Insert(0, GetNodeDirectory(installdir, nsm));
                            installationPath.Insert(0, GetDirectoryPath(installdir, nsm));
                        }
                    }
                }
            }

            return installationPath.ToString();
        }
        public override ActionResult ApplyActionTo(StringBuilder sb)
        {
            int searchStart = FieldToChange.TextRange.StartOffset;
            int searchEnd = FieldToChange.TextRange.EndOffset;
            string text = sb.ToString();

            if (InsertAtStart)
            {
                sb.Insert(searchStart, NewModifier + " ");
                FieldToChange.Modifiers.Insert(0, NewModifier);
                return new ActionResult(searchStart, NewModifier.Length + 1, null);
            }

            int nameIndex = InsertionHelpers.GetFieldNameIndex(text, FieldToChange, searchStart, searchEnd);

            // Search Field TextRange for class keyword
            // The last "word" between the start of the field and the name is the type.
            var substring = text.Substring(0, nameIndex);
            string typeName = InsertionHelpers.GetLastWord(substring);
            if (typeName == null)
            {
                log.ErrorFormat("Could not find type of property {0} to change, so can't insert modifier before it.", FieldToChange.Name);
                return new ActionResult();
            }

            // Find the index of the existing type
            int typeIndex = substring.LastIndexOf(typeName);

            //Insert the new modifier just before the class keyword
            sb.Insert(typeIndex, NewModifier + " ");
            FieldToChange.Modifiers.Add(NewModifier);

            return new ActionResult(typeIndex, NewModifier.Length + 1, null);
        }
        /// <summary>
        /// Inserts spaces where the string contains camel-casing or underscores
        /// </summary>
        /// <param name="s">The string to process</param>
        /// <returns>The string with spaces inserted</returns>
        public static string InsertSpaces(this string s)
        {
            if (string.IsNullOrWhiteSpace(s))
                return s;

            StringBuilder sb = new StringBuilder();
            for (int i = s.Length - 1; i >= 0; i--)
            {
                char c = s[i];
                if (char.IsUpper(c))
                {
                    // For a capital letter, we add a space before
                    sb.Insert(0, new char[] { c });
                    sb.Insert(0, new char[] { ' ' });
                }
                else if (c == '_')
                {
                    // replace underscores with a space
                    sb.Insert(0, new char[] { ' ' });
                }
                else
                {
                    sb.Insert(0, new char[] { c });
                }
            }
            return sb.ToString().Trim();
        }
Beispiel #4
0
        // This function loop List of camlqueryelments which has our filter criteria
        // Then generate query in required format.
        // At end it return string which holds caml query.
        public static string GenerateQuery(IList<CamlQueryElements> queryElements)
        {
            StringBuilder queryJoin = new StringBuilder();
            string query = @"<{0}><FieldRef Name='{1}' /><Value {2} Type='{3}'>{4}</Value></{5}>";
            if (queryElements.Count > 0)
            {
                int itemCount = 0;
                foreach (CamlQueryElements element in queryElements)
                {
                    itemCount++;
                    string date = string.Empty;
                    // Display only Date
                    if (String.Compare(element.FieldType, "DateTime", true) == 0)
                        date = "IncludeTimeValue='false'";
                    queryJoin.AppendFormat
                   (string.Format(query, element.ComparisonOperators, element.FieldName,
                       date, element.FieldType, element.FieldValue, element.ComparisonOperators));

                    if (itemCount >= 2)
                    {
                        queryJoin.Insert(0, string.Format("<{0}>", element.LogicalJoin));
                        queryJoin.Append(string.Format("</{0}>", element.LogicalJoin));
                    }
                }
                queryJoin.Insert(0, "<Where>");
                queryJoin.Append("</Where>");
            }
            return queryJoin.ToString();
        }
Beispiel #5
0
        public static string FromUpcA(string value)
        {
            if (!Regex.IsMatch(value, @"^[01]\d{2}([012]0{4}\d{3}|[3-9]0{4}\d{2}|\d{4}0{4}\d|\d{5}0{4}[5-9])"))
                throw new ArgumentException("UPC A code cannot be compressed.");

            StringBuilder result = new StringBuilder(value);

            if (result[5] != '0')
                result.Remove(6, 4);
            else if (result[4] != '0')
            {
                result.Remove(5, 5);
                result.Insert(6, "4");
            }
            else if (result[3] != '2' && result[3] != '1' && result[3] != '0')
            {
                result.Remove(4, 5);
                result.Insert(6, "3");
            }
            else
            {
                result.Insert(11, result[3]);
                result.Remove(3, 5);
            }

            return result.ToString();
        }
        public override ActionResult ApplyActionTo(StringBuilder sb)
        {
            int searchStart = FieldToChange.TextRange.StartOffset;
            int searchEnd = FieldToChange.TextRange.EndOffset;
            string text = sb.ToString();

            int nameIndex = InsertionHelpers.GetFieldNameIndex(text, FieldToChange, searchStart, searchEnd);
            int endOfNameIndex = nameIndex + FieldToChange.Name.Length + 1;

            // Find the old initial value and remove it, if it exists
            int lengthRemoved = searchEnd - endOfNameIndex;

            sb.Remove(endOfNameIndex, lengthRemoved);
            string textToInsert = "";

            if (!string.IsNullOrWhiteSpace(NewInitialValue))
            {
                textToInsert = string.Format(" = {0};", NewInitialValue);
                sb.Insert(endOfNameIndex + 1, textToInsert);
            }
            // Add the new modifier only if it is not null
            if (string.IsNullOrEmpty(NewInitialValue))
            {
                FieldToChange.InitialValue = "";
                return new ActionResult(searchStart, -lengthRemoved, null);
            }

            sb.Insert(searchStart, NewInitialValue + " ");
            FieldToChange.InitialValue = NewInitialValue;
            return new ActionResult(searchStart, textToInsert.Length + 1 - lengthRemoved, null);
        }
        public static string ConvertToNumberByWordsString(decimal val, bool male)
        {
            bool minus = false;
            if (val < 0) { val = -val; minus = true; }

            var n = (int)val;

            var r = new StringBuilder();

            if (0 == n) r.Append("ноль ");
            if (n % 1000 != 0)
                r.Append(NumToStr(n, male, "", "", ""));
            else
                r.Append("");

            n /= 1000;

            r.Insert(0, NumToStr(n, false, "тысяча", "тысячи", "тысяч"));
            n /= 1000;

            r.Insert(0, NumToStr(n, true, "миллион", "миллиона", "миллионов"));
            n /= 1000;

            r.Insert(0, NumToStr(n, true, "миллиард", "миллиарда", "миллиардов"));
            n /= 1000;

            r.Insert(0, NumToStr(n, true, "триллион", "триллиона", "триллионов"));
            n /= 1000;

            r.Insert(0, NumToStr(n, true, "триллиард", "триллиарда", "триллиардов"));
            if (minus) r.Insert(0, "минус ");

            return r.ToString().Trim();
        }
        public override string ToString()
        {
            var textBuilder = new StringBuilder();

            for (int offset = 0; offset < BitCount; offset++)
            {
                int shift = BitCount - offset - 1;
                bool bitIsSet = (Value & ((ulong) 1 << shift)) != 0;
                textBuilder.Append(bitIsSet ? '1' : '0');
            }

            // Add leading zeros when not whole nibbles.
            while (textBuilder.Length % 4 != 0)
            {
                textBuilder.Insert(0, '0');
            }

            // Insert dot (.) between nibbles.
            for (int index = textBuilder.Length - 4; index > 0; index -= 4)
            {
                textBuilder.Insert(index, '.');
            }

            return textBuilder.ToString();
        }
 public static string FindXPath(XmlNode node)
 {
     var builder = new StringBuilder();
     while (node != null)
     {
         switch (node.NodeType)
         {
             case XmlNodeType.Attribute:
                 builder.Insert(0, "/@" + node.Name);
                 node = ((XmlAttribute)node).OwnerElement;
                 break;
             case XmlNodeType.Element:
                 var index = FindElementIndex((XmlElement)node);
                 builder.Insert(0, "/" + node.Name + "[" + index + "]");
                 node = node.ParentNode;
                 break;
             case XmlNodeType.Document:
                 return builder.ToString();
             default:
                 throw new ArgumentException("Only elements and attributes are supported");
         }
     }
     return "*";
     //            throw new ArgumentException("Node was not in a document");
 }
		private string makeWhere(Uri url)
		{
			Stack<string> hostStack = new Stack<string>(url.Host.Split('.'));
			StringBuilder hostBuilder = new StringBuilder('.' + hostStack.Pop());
			string[] pathes = url.Segments;

			StringBuilder sb = new StringBuilder();
			sb.Append("WHERE (");

			bool needOr = false;
			while (hostStack.Count != 0) {
				if (needOr) {
					sb.Append(" OR");
				}

				if (hostStack.Count != 1) {
					hostBuilder.Insert(0, '.' + hostStack.Pop());
					sb.AppendFormat(" host = \"{0}\"", hostBuilder.ToString());
				} else {
					hostBuilder.Insert(0, '%' + hostStack.Pop());
					sb.AppendFormat(" host LIKE \"{0}\"", hostBuilder.ToString());
				}

				needOr = true;
			}

			sb.Append(')');
			return sb.ToString();
		}
Beispiel #11
0
        /// <summary>
        /// Returns a string representation of the BitArray object.
        /// </summary>
        /// <param name="bits">The BitArray object to convert to string.</param>
        /// <returns>A string representation of the BitArray object.</returns>
        public static string ToString(System.Collections.BitArray bits)
        {
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            if (bits != null)
            {
                for (int i = 0; i < bits.Length; i++)
                {
                    if (bits[i] == true)
                    {
                        if (s.Length > 0)
                        {
                            s.Append(", ");
                        }
                        s.Append(i);
                    }
                }

                s.Insert(0, "{");
                s.Append("}");
            }
            else
            {
                s.Insert(0, "null");
            }

            return(s.ToString());
        }
		private string GenerateExpression(Expression expression)
		{
			var sb = new StringBuilder();
			var memberReferenceExpression = expression as MemberReferenceExpression;
			while (memberReferenceExpression != null)
			{
				if (sb.Length != 0)
					sb.Insert(0, ".");

				sb.Insert(0, memberReferenceExpression.MemberName);

				expression = memberReferenceExpression.TargetObject;
				memberReferenceExpression = expression as MemberReferenceExpression;
			}

			var identifierExpression = expression as IdentifierExpression;
			if(identifierExpression != null && sb.Length != 0)
			{
				string path;
				if (aliasToName.TryGetValue(identifierExpression.Identifier, out path))
				{
					sb.Insert(0, path);
				}
			}
			if (sb.Length == 0)
				return null;

			return sb.ToString();
		}
        public static string formatCurrencyText(string content, string _preFix, char _thousandsSeparator, char _decimalsSeparator)
        {
            int _decimalPlaces = 0;
            int counter = 1;
            int counter2 = 0;
            char[] charArray = content.ToCharArray();
            StringBuilder str = new StringBuilder();

            for (int i = charArray.Length - 1; i >= 0; i--)
            {
                str.Insert(0, charArray.GetValue(i));
                if (_decimalPlaces == 0 && counter == 3)
                {
                    counter2 = counter;
                }

                if (counter == _decimalPlaces && i > 0)
                {
                    if (_decimalsSeparator != Char.MinValue)
                        str.Insert(0, _decimalsSeparator);
                    counter2 = counter + 3;
                }
                else if (counter == counter2 && i > 0)
                {
                    if (_thousandsSeparator != Char.MinValue)
                        str.Insert(0, _thousandsSeparator);
                    counter2 = counter + 3;
                }
                counter = ++counter;
            }
            return (_preFix != "" && str.ToString() != "") ? _preFix + " " + str.ToString() : (str.ToString() != "") ? str.ToString() : "";
        }
        public static string GetFullMetadataName([NotNull] this INamespaceOrTypeSymbol symbol)
        {
            Guard.NotNull(symbol, nameof(symbol));

            ISymbol current = symbol;
            var textBuilder = new StringBuilder(current.MetadataName);

            ISymbol previous = current;
            current = current.ContainingSymbol;
            while (!IsRootNamespace(current))
            {
                if (current is ITypeSymbol && previous is ITypeSymbol)
                {
                    textBuilder.Insert(0, '+');
                }
                else
                {
                    textBuilder.Insert(0, '.');
                }
                textBuilder.Insert(0, current.MetadataName);
                current = current.ContainingSymbol;
            }

            return textBuilder.ToString();
        }
Beispiel #15
0
        public string AddBinary(string a, string b)
        {
            var carry = 0;
            var builder = new StringBuilder();

            var aLength = a.Length - 1;
            var bLength = b.Length - 1;

            int aVal, bVal, val;
            while (aLength >= 0 || bLength >= 0)
            {
                aVal = aLength >= 0 ? a[aLength] - '0' : 0;
                bVal = bLength >= 0 ? b[bLength] - '0' : 0;

                val = aVal + bVal + carry;
                builder.Insert(0, val & 1);

                carry = val >> 1;

                aLength--;
                bLength--;
            }

            if (carry >= 1)
            {
                builder.Insert(0, carry);
            }

            return builder.ToString();
        }
 static void Main(string[] args)
 {
     Console.Write("Please enter signed 16bit integer: ");
     string inputStr = Console.ReadLine();
     short number = short.Parse(inputStr);
     StringBuilder result = new StringBuilder();
     if (number >= 0)
     {
         int workingNum = number;
         for (int i = 0; i < 16; i++)
         {
             int temp = workingNum % 2;
             workingNum = workingNum / 2;
             result.Insert(0, temp);
         }
     }
     else
     {
         int workingNum = Math.Abs(number) - 1;
         for (int i = 0; i < 16; i++)
         {
             int temp = workingNum % 2;
             workingNum = workingNum / 2;
             if (temp == 0)
             {
                 result.Insert(0, '1');
             }
             else
             {
                 result.Insert(0, '0');
             }
         }
     }
     Console.WriteLine("In Binary {0} equals {1}", inputStr, result.ToString());
 }
Beispiel #17
0
        static string FindXPath(XmlNode node)
        {
            StringBuilder builder = new StringBuilder();
            while (node != null) {
                switch (node.NodeType) {
                    case XmlNodeType.Attribute:
                        builder.Insert(0, "/@" + node.Name);
                        node = ((XmlAttribute)node).OwnerElement;
                        break;
                    case XmlNodeType.Text:
                        builder.Insert(0, "/text()");
                        node = node.ParentNode;
                        break;
                    case XmlNodeType.Element:
                        int index = FindElementIndex((XmlElement)node);
                        if (string.Equals(node.Name, "Component")) {
                            builder.Insert(0, "/" + node.Name + "[@Code=\'" + node.Attributes["Code"].Value + "\']");
                        } else {
                            builder.Insert(0, "/" + node.Name + "[" + index + "]");

                        }
                        node = node.ParentNode;
                        break;
                    case XmlNodeType.Document:
                        return builder.ToString();
                    default:
                        throw new ArgumentException("Only elements and attributes are supported");
                }
            }
            throw new ArgumentException("Node was not in a document");
        }
        private static string Encode(StringBuilder finalString)
        {
            int counterOccurance = 1;
            char ch = ' ';

            for (int i = 0; i < finalString.Length - 1; i++)
            {
                if (finalString[i] == finalString[i + 1])
                {
                    counterOccurance++;
                    ch = finalString[i];
                }

                else if (counterOccurance > 2 && counterOccurance < finalString.Length -1
                    && finalString[i] != finalString[i + 1])
                {
                    finalString.Remove(i - (counterOccurance - 1), counterOccurance);
                    finalString.Insert(i - counterOccurance + 1, counterOccurance);
                    finalString.Insert(i - (counterOccurance - counterOccurance.ToString().Length - 1), ch);

                }
                if ((i < finalString.Length - 1) && finalString[i] != finalString[i + 1])
                {
                    counterOccurance = 1;
                }

            }
            return finalString.ToString();
        }
Beispiel #19
0
        static void Main()
        {
            string chochkosBulshit = Console.ReadLine();

            var ragePattern = new Regex(@"(?<rage>[^\d]{1,20})(?<count>\d{1,2})");

            var uniqueSymbols = new HashSet<char>();

            var resultBuilder = new StringBuilder();

            foreach (Match m in ragePattern.Matches(chochkosBulshit))
            {
                string rage = m.Groups["rage"].Value.ToUpper();

                int repetitions;
                int.TryParse(m.Groups["count"].Value, out repetitions);

                if (repetitions != 0)
                {
                    foreach (char c in rage)
                    {
                        uniqueSymbols.Add(c);
                    }

                    resultBuilder.Insert(resultBuilder.Length, rage, repetitions);
                }
            }

            resultBuilder.Insert(0, string.Format("Unique symbols used: {0}\n", uniqueSymbols.Count));

            Console.WriteLine(resultBuilder.ToString());
        }
Beispiel #20
0
        public BackupViewer(Main main)
        {
            InitializeComponent();

            _Main = main;
            this.Icon = Me.Amon.Hosts.Properties.Resources.Icon;

            if (Directory.Exists(Main.BAK_DIR))
            {
                string name;
                StringBuilder text = new StringBuilder();
                foreach (string file in Directory.GetFiles(Main.BAK_DIR, string.Format(Main.HOSTS_FILE, "*")))
                {
                    name = Path.GetFileName(file);
                    name = name.Substring(6);
                    if (name.Length != 14)
                    {
                        continue;
                    }

                    text.Append(name);
                    text.Insert(12, ':').Insert(10, ':');
                    text.Insert(8, ' ');
                    text.Insert(6, '-').Insert(4, '-');
                    LbBak.Items.Add(new KVItem { K = name, V = text.ToString() });
                    text.Clear();
                }
            }
        }
        /// <summary>
        /// Formats the entered text.
        /// </summary>
        /// <returns></returns>
        public string formataTexto(string textoFormatar)
        {
            this.WorkingText = textoFormatar.Replace((_thousandsSeparator.ToString() != "") ? _thousandsSeparator.ToString() : " ", String.Empty)
                                        .Replace((_decimalsSeparator.ToString() != "") ? _decimalsSeparator.ToString() : " ", String.Empty).Trim();
            int counter = 1;
            int counter2 = 0;
            char[] charArray = this.WorkingText.ToCharArray();
            StringBuilder str = new StringBuilder();

            for (int i = charArray.Length - 1; i >= 0; i--)
            {
                str.Insert(0, charArray.GetValue(i));
                if (_decimalPlaces == 0 && counter == 3)
                {
                    counter2 = counter;
                }

                if (counter == _decimalPlaces && i > 0)
                {
                    if (_decimalsSeparator != Char.MinValue)
                        str.Insert(0, _decimalsSeparator);
                    counter2 = counter + 3;
                }
                else if (counter == counter2 && i > 0)
                {
                    if (_thousandsSeparator != Char.MinValue)
                        str.Insert(0, _thousandsSeparator);
                    counter2 = counter + 3;
                }
                counter = ++counter;
            }

            string retorno = (str.ToString() != "") ? str.ToString() : (str.ToString() != "") ? str.ToString() : "";
            return retorno;
        }
		public static string ConvertShortcutToString(Shortcut shortcut)
		{
			string shortcutString = Convert.ToString(shortcut);
			StringBuilder result = new StringBuilder(shortcutString);

			if (shortcutString.StartsWith("Alt"))
			{
				result.Insert(3, " + ");
			}
			else if (shortcutString.StartsWith("CtrlShift"))
			{
				result.Insert(9, " + ");
				result.Insert(4, " + ");
			}
			else if (shortcutString.StartsWith("Ctrl"))
			{
				result.Insert(4, " + ");
			}
			else if (shortcutString.StartsWith("Shift"))
			{
				result.Insert(5, " + ");
			}

			return result.ToString();
		}
        private string ConvertNumberToString(int number)
        {
            int tenPow = 1;
            StringBuilder retSb = new StringBuilder();
            do
            {
                int valueRedunt;
                int valueUnit;
                tenPow *= 10;

                valueRedunt = number % tenPow;
                valueUnit = valueRedunt / (tenPow / 10);

                retSb.Insert(0, " ");
                retSb.Insert(0, DecimalPositionalToString((DecimalPositional)tenPow));
                retSb.Insert(0, " ");
                retSb.Insert(0, valueUnit);
            }while(number/tenPow > 0);

            retSb.Insert(0, " ");
            retSb.Insert(0, "có:");
            retSb.Insert(0, " ");
            retSb.Insert(0, number);
            retSb.Insert(0, " ");
            retSb.Insert(0, "Số");

            return retSb.ToString();
        }
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            string uformat = format.ToUpper(CultureInfo.InvariantCulture);
            if (arg == null || uformat != "HEX")
                return string.Format(parentProvider, "{0:" + format + "}", arg);

            if (arg.GetType() != typeof(int) && arg.GetType() != typeof(long))
                return string.Format(parentProvider, "{0:" + format + "}", arg);

            StringBuilder resultStr = new StringBuilder();

            long number = Convert.ToInt64(arg);
            bool minuse = false;
            if (number < 0)
            {
                number = Math.Abs(number);
                minuse = true;
            }

            do
            {
                int symbol = (int)(number % 16);
                resultStr.Insert(0, unitBase[symbol]);
                number /= 16;
            } while (number > 0);

            if (minuse)
                resultStr.Insert(0, "-");

            return "0x" + resultStr;
        }
Beispiel #25
0
        private void btnEditPhoneNumber_Click(object sender, System.EventArgs e)
        {
            string enteredPhone = txtPhoneNumber.Text;
            StringBuilder phoneNumber = new StringBuilder(enteredPhone, 14);

            // Phone number currently looks like this: (xxx) xxx-xxxx

            // Covered on page 271 in book.
            phoneNumber.Remove(0, 1);   // xxx) xxx-xxxx
            phoneNumber.Remove(3, 2);   // xxxxxx-xxxx
            phoneNumber.Remove(6, 1);   // xxxxxxxxxx

            string onlyNumbersPhone = phoneNumber.ToString();

            phoneNumber.Insert(3, "-"); // xxx-xxxxxxx
            phoneNumber.Insert(7, "-"); // xxx-xxx-xxxx

            string standardPhone = phoneNumber.ToString();

            string msg = "Entered:\t\t" + enteredPhone + "\n"
                + "Digits Only:\t" + onlyNumbersPhone + "\n"
                + "Standard Format:\t" + standardPhone;

            MessageBox.Show(msg, "Edit Phone Number");
        }
        static void Main()
        {
            StringBuilder cages = new StringBuilder();

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "END")
                {
                    break;
                }
                cages.Append(input);
            }

            int cagesToTake = int.Parse((cages[0] - '0').ToString());
            
            int cagesToRemove = 1;

            while (cagesToTake < cages.Length)
            {
                cages.Remove(0, cagesToRemove);
                BigInteger sum = 0;
                BigInteger product = 1;
                
                for (int i = 0; i < cagesToTake; i++)
                {
                    sum += BigInteger.Parse((cages[i] - '0').ToString());
                    product *= BigInteger.Parse((cages[i] - '0').ToString());
                    cages.Insert(0, "*", 1);
                    cages.Remove(0, 1);
                }
                string digitsToAppend = AppendTheSumAndProduct(cages, sum, product);
               
                cages.Remove(0, cagesToTake);
                cages.Insert(0, digitsToAppend); 

                if (cagesToRemove >= cages.Length)
                {
                    break;
                }

                cagesToRemove++;

                int cagesToSum = cagesToRemove;
                cagesToTake = SumOfDigitsToAppend(digitsToAppend, cagesToRemove);
            }

            for (int i = 0; i < cages.Length; i++)
            {
                if (i != cages.Length - 1)
                {
                    Console.Write("{0} ", cages[i]);
                }
                else
                {
                    Console.WriteLine(cages[i]);
                }
                
            }
        }
        /// <summary>
        /// Encloses each pattern substring in the target string with highlight tag.
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="target"></param>
        /// <param name="pattern"></param>
        /// <param name="highlightTag"></param>
        /// <returns></returns>
        public static MvcHtmlString HighlightPattern(this HtmlHelper helper, string target, string pattern, string highlightTag)
        {
            // This is a dirty code which encloses with tags every pattern match .
            // And in the same time save the original case of the pattern match.
            // I know it can be achieved with one regular expression. But I don't know this expression.

            var openTag = String.Format("<{0}>", highlightTag);
            var closeTag = String.Format("</{0}>", highlightTag);
            var builder = new StringBuilder(target);

            if (!string.IsNullOrEmpty(pattern))
            {

                var match = Regex.Match(target, pattern, RegexOptions.IgnoreCase);

                int count = 0;
                while (match.Success)
                {
                    builder.Insert(match.Index + count, openTag);
                    count += openTag.Length;
                    builder.Insert(match.Index + match.Length + count, closeTag);
                    count += closeTag.Length;
                    match = match.NextMatch();
                }
            }
            return new MvcHtmlString(builder.ToString());
        }
        public FlattenedSection FlattenSection(Section section)
        {
            var words = section.SectionText.Split(' ');
            FlattenedSection flatSection = new FlattenedSection
            {
                SectionId = section.SectionId,
                DatasheetId = section.DatasheetId,
                StringSections = new List<StringSection>(words.Length * (words.Length -1))
            };

            for (int i = 0; i < words.Length; i++)
            {
                StringBuilder builder = new StringBuilder();
                //add all words before to before this string and save
                for (int j = i; j > -1; j--) //iterate backwards from current word to beginning
                {
                    builder.Insert(0,words[j]); //add the word at j
                    flatSection.StringSections.Add(FlattenWord(builder.ToString(),section.DatasheetId,flatSection.SectionId));
                    builder.Insert(0, ' ');
                }

                builder.Clear();
                //add all words to after this string and save
                for (int j = i; j < words.Length; j++)
                {
                    builder.Append(words[j]);
                    flatSection.StringSections.Add(FlattenWord(builder.ToString(),section.DatasheetId,section.SectionId));
                    builder.Append(' ');
                }
            }

            return flatSection;
        }
 private static string stringify(FbDataReader reader, string parentnodename)
 {
     StringBuilder json = new StringBuilder();
     int columns = reader.FieldCount;
     if (parentnodename.Length > 0) { json.AppendFormat("{{\"{0}\":", parentnodename); }
     while (reader.Read())
     {
         for (int i = 0; i < columns; i++)
         {
             if (i % reader.FieldCount == 0) { json.Append("{"); }
             json.AppendFormat("\"{0}\":{1},", reader.GetName(i).ToLower(), jsonify(reader.GetValue(i)));
             if (i % reader.FieldCount == reader.FieldCount - 1)
             {
                 json.Remove(json.Length - 1, 1);
                 json.Append("},");
             }
         }
     }
     // if nothing (or only the parentnodename is appended to the string builder then the reader was empty and we return nothing. reader.HasRows doesn't work
     if (json.Length == 0 || json.ToString() == string.Format("{{\"{0}\":", parentnodename)) { return ""; }
     json.Remove(json.Length - 1, 1);
     if (parentnodename.Length > 0) { json.Append("}"); }
     // check if the json should contain an array and add array structure if true
     if (Regex.IsMatch(json.ToString(), "},{"))
     {
         json.Insert((parentnodename.Length > 0 ? parentnodename.Length + 4 : 4), "[");
         json.Insert(json.Length - 1, "]");
     }
     return json.ToString();
 }
        static string ConvertToOtherNumericSystem(long number, int system)
        {
            if (number < 1)
            {
                throw new ArgumentException("The given number must be greater than 0!");
            }
            if (system < 0)
            {
                throw new ArgumentException("The given system is smaller than 0!");
            }

            long remainder = 0;
            long tempNumber = number;
            StringBuilder binary = new StringBuilder();

            while (tempNumber > 0)
            {
                int index = 0;
                remainder = tempNumber % system;
                if (remainder >= 10 && remainder <= 22)
                {
                    binary.Insert(index, (char)(remainder + 'a'));
                }
                else
                {
                    binary.Insert(index, (char)(remainder + 'a'));
                }
                tempNumber /= system;
                index++;
            }
            return binary.ToString();
        }
Beispiel #31
0
 public string[] flareOut(string[] snowflake)
 {
     string[] temp = new string[snowflake.Length];
     for (int i = 0; i < snowflake[snowflake.Length - 1].Length; i++)
     {
         StringBuilder sb = new StringBuilder();
         for (int a = snowflake.Length - 1; a > i; a--)
         {
             sb.Insert(0, snowflake[a][i].ToString());
         }
         if (sb.ToString() == "")
             temp[i] = snowflake[i];
         else
         {
             sb.Insert(0, snowflake[i]);
             temp[i] = sb.ToString();
         }
     }
     for (int i = 0; i < temp.Length; i++)
     {
         StringBuilder sb = new StringBuilder();
         for (int a = temp[i].Length - 1; a >= 0; a--)
             sb.Append(temp[i][a].ToString());
         sb.Append(temp[i]);
         temp[i] = sb.ToString();
     }
     string[] result = new string[temp.Length * 2];
     int x = -1;
     for (int i = temp.Length - 1; i >= 0; i--)
         result[++x] = temp[i];
     for (int i = 0; i < temp.Length; i++)
         result[++x] = temp[i];
     return result;
 }
        public static string IncrementAnyString(string pstrInputNumber, ref string pref_sErrorMessage, bool pbFormatCommas)
        {
            //
            //Added 4/9/2020 thomas downes
            //
            //  Let's make this very fast.
            //
            char charCurrDigit = ' ';
            //pstrInputNumber = pstrInputNumber.Trim();

            //
            //https://stackoverflow.com/questions/8987141/how-to-change-1-char-in-the-string
            //
            //-----var stringBuild = new System.Text.StringBuilder(1 + pstrInputNumber.Length);
            var    stringBuild                = new System.Text.StringBuilder(pstrInputNumber.Trim());
            string sErrorMessage              = "";
            char   charIncremented            = ' ';
            bool   bCarryTheOne_NextOperation = false;
            int    intIndexOfBiggestComma     = -1;

            for (int intCharIndex = -1 + pstrInputNumber.Length; intCharIndex >= 0; intCharIndex--)
            {
                charCurrDigit = stringBuild[intCharIndex];

                charIncremented = IncrementDigit(charCurrDigit, ref bCarryTheOne_NextOperation, ref sErrorMessage);

                stringBuild[intCharIndex] = charIncremented;

                if (pbFormatCommas && charCurrDigit == ',')
                {
                    intIndexOfBiggestComma = intCharIndex;
                }

                if (false == bCarryTheOne_NextOperation)
                {
                    break;
                }
            }

            //
            // If we are incrementing a sequence of 9's (e.g. 99 or 999) then we need to put
            //     a single digit of 1 right in front of all the 0s (e.g. 00 or 000).
            //
            if (bCarryTheOne_NextOperation)
            {
                // Insert a comma, if needed.
                if (intIndexOfBiggestComma == 3)
                {
                    stringBuild.Insert(0, ',');
                }
                if ("999" == stringBuild.ToString())
                {
                    stringBuild.Insert(0, ',');
                }
                stringBuild.Insert(0, '1');
            }

            return(stringBuild.ToString());
        }
Beispiel #33
0
        public static string ParseOrcbrewFile(string input)
        {
            StringBuilder sFileString = new System.Text.StringBuilder(input);

            bool removed  = false;
            bool inString = false;

            for (int i = 0; i < sFileString.Length; i++)
            {
                char cChar = sFileString[i];
                if (cChar.Equals('\\') && sFileString[i + 1] == 'n')   //Removes new lines added by OrcPub
                {
                    sFileString.Remove(i, 2);
                }
                if (cChar.Equals('"'))                                           //Toggles between being in a value field and a key field
                {
                    inString = !inString;                                        //To avoid editing values
                }
                if (cChar.Equals(':') && sFileString[i + 1] != ' ' && !inString) //Removes colon from the start of a key
                {
                    sFileString[i] = '"';                                        //Adds starting " to key name
                    removed        = true;                                       //Indicates that the colon has been removed, and a " will be required at the end of the word
                    continue;
                }
                if (removed && cChar.Equals('}'))               //Corner case for adding " to the end of an entry
                {
                    sFileString.Insert(i, "\"");
                    i       = i + 1;
                    removed = false;
                    continue;
                }
                if (removed && cChar.Equals(','))              //Corner case for adding " to the end of an entry
                {
                    sFileString.Insert(i, "\"");
                    i       = i + 1;
                    removed = false;
                    continue;
                }
                if (removed && Char.IsWhiteSpace(cChar))        //Adds " to the end of the word
                {
                    sFileString.Insert(i, "\": ");
                    i       = i + 2;
                    removed = false;
                    continue;
                }
                if (cChar.Equals('}'))                      //Adds a comma between array values
                {
                    if (i < sFileString.Length - 2 && sFileString[i + 1] == ' ' && sFileString[i + 2] == '{')
                    {
                        sFileString.Insert(i + 1, ',');
                        i = i + 2;
                    }
                    continue;
                }
            }

            return(sFileString.ToString());              //return string of JSON format
        }
Beispiel #34
0
 static public string GetServerlUrl(string path, string serverName, RuntimePlatform platformType)
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(platformType.ToString(), 100);
     stringBuilder.Append(@"/");
     stringBuilder.Append(@path);
     stringBuilder.Insert(0, @"/");
     stringBuilder.Insert(0, serverName);
     return(stringBuilder.ToString());
 }
Beispiel #35
0
 static public string GetLocalUrl(string path, bool isInApp, RuntimePlatform platformType)
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(platformType.ToString(), 100);
     stringBuilder.Append(@"/");
     stringBuilder.Append(@path);
     stringBuilder.Insert(0, @"/");
     stringBuilder.Insert(0, isInApp ? Application.streamingAssetsPath : Application.persistentDataPath);
     return(stringBuilder.ToString());
 }
Beispiel #36
0
    public static string GetTransformPath(Transform t, char separator = '/')
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder(t.name);
        Transform current            = t;

        while (current.parent != null)
        {
            sb.Insert(0, separator);
            sb.Insert(0, current.parent.name);
            current = current.parent;
        }
        return(sb.ToString());
    }
    public static string GetHierarchyPath(this Transform transform)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.AppendFormat("/{0}", transform.name);
        while (transform.parent != null)
        {
            transform = transform.parent;
            sb.Insert(0, transform.name);
            sb.Insert(0, "/");
        }
        return(sb.ToString());
    }
Beispiel #38
0
    static void Main()
    {
        System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("bg-BG");
        System.Globalization.CultureInfo.DefaultThreadCurrentCulture = culture;
        int startYear   = int.Parse(Console.ReadLine());
        int endYear     = int.Parse(Console.ReadLine());
        int magicWeight = int.Parse(Console.ReadLine());
        int counter     = 0;

        for (int k = startYear; k <= endYear; k++)
        {
            for (int j = 1; j <= 12; j++)
            {
                for (int i = 1; i <= 31; i++)

                {
                    int number = i * 1000000 + j * 10000 + k;
                    int h      = number % 10;
                    int g      = number / 10 % 10;
                    int f      = number / 100 % 10;
                    int e      = number / 1000 % 10;
                    int d      = number / 10000 % 10;
                    int c      = number / 100000 % 10;
                    int b      = number / 1000000 % 10;
                    int a      = number / 10000000;

                    int p = a * b + a * c + a * d + a * e + a * f + a * g + a * h + b * c + b * d + b * e + b * f + b * g + b * h + c * d + c * e + c * f + c * g + c * h + d * e + d * f + d * g + d * h + e * f + e * g + e * h + f * g + f * h + g * h;

                    if (p == magicWeight)
                    {
                        string numberToDate          = number.ToString();
                        System.Text.StringBuilder sb = new System.Text.StringBuilder(numberToDate);
                        sb.Insert(numberToDate.Length - 4, "-");
                        sb.Insert(numberToDate.Length - 6, "-");
                        numberToDate = sb.ToString();
                        DateTime date;
                        bool     isDate = DateTime.TryParse(numberToDate, out date);
                        if (isDate == true)
                        {
                            Console.WriteLine("{0:dd-MM-yyyy}", date);
                            counter++;
                        }
                    }
                }
            }
        }
        if (counter == 0)
        {
            Console.WriteLine("No");
        }
    }
Beispiel #39
0
        /// <summary>
        /// Perform mapping for each character of input.
        /// </summary>
        /// <param name="result">Result is modified in place.</param>
        public override void Prepare(System.Text.StringBuilder result)
        {
            // From RFC3454, section 3: Mapped characters are not
            // re-scanned during the mapping step.  That is, if
            // character A at position X is mapped to character B,
            // character B which is now at position X is not checked
            // against the mapping table.
            int pos;
            string map;
            int len;
            for (int i=0; i<result.Length; i++)
            {
                pos = Array.BinarySearch(m_table, result[i], m_comp);
                if (pos < 0)
                    continue;

                map = m_table[pos];
                len = map.Length;
                if (len == 1)
                {
                    result.Remove(i, 1);
                    i--;
                }
                else
                {
                    result[i] = map[1];
                    if (len > 2)
                    {
                        result.Insert(i+1, map.ToCharArray(2, len - 2));
                        i += len - 2;
                    }
                }
            }
        }
        /// <summary>
        /// Indicates whether the regular expression specified in "pattern" could be found in the "text".
        /// </summary>
        /// <param name="text">The string to search for a match</param>
        /// <param name="pattern">The pattern to find in the "text" string (supports the *, ? and # wildcard characters).</param>
        /// <param name="ignoreCase">True for a case-insensitive match.</param>
        /// <returns>Returns true if the regular expression finds a match otherwise returns false.</returns>
        /// <remarks>
        /// ?			Matches any single character (between A-Z and a-z)
        /// #			Matches any single digit. For example, 7# matches numbers that include 7 followed by another number, such as 71, but not 17.
        /// *			Matches any one or more characters. For example, new* matches any text that includes "new", such as newfile.txt.
        ///
        /// This functionality is based on the following article:
        /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxgrfwildcards.asp
        ///
        /// Thanks to Stefan Schletterer for corrections.
        /// </remarks>
        public static bool Like(string text, string pattern, bool ignoreCase)
        {
            // Check input parameters
            if (pattern == null || text == null || pattern.Length == 0 || text.Length == 0 || pattern == "*.*" == true)
            {
                // Default return is true
                return(true);
            }

            // Escape all strings
            System.Text.StringBuilder regPattern = new System.Text.StringBuilder(Regex.Escape(pattern));

            // Replace the LIKE patterns with regular expression patterns
            regPattern = regPattern.Replace(Regex.Escape("*"), ".*");
            regPattern = regPattern.Replace(Regex.Escape("?"), @".");
            regPattern = regPattern.Replace(Regex.Escape("#"), @"[0-9]");
            regPattern = regPattern.Replace(Regex.Escape("[!"), @"[!");
            regPattern = regPattern.Replace(Regex.Escape("["), @"[");
            regPattern = regPattern.Replace(Regex.Escape("]"), @"]");

            // Add begin and end blocks (to match on the whole string only)
            regPattern.Insert(0, "^");
            regPattern.Append("$");

            if (ignoreCase == false)
            {
                return(Regex.IsMatch(text, regPattern.ToString()));
            }
            else
            {
                return(Regex.IsMatch(text, regPattern.ToString(), RegexOptions.IgnoreCase));
            }
        }
    public void UpdateDeadPanel(EnemyType enemyType)
    {
        if (gameManager == null)
        {
            gameManager = FindObjectOfType <GameManager>();
        }
        characterReader = gameManager.characterReader;
        skilldata       = characterReader.GetEnemySkillUI(enemyType.ToString());
        data            = characterReader.GetEnemyData(gameManager.enemyManager.getEnemyLevel(enemyType), enemyType.ToString());

        txtname.text  = enemyType.ToString();
        txtdata1.text = gameManager.enemyManager.getEnemyLevel(enemyType) + "\n" + data.HP + "\n" + data.attack + "\n" + data.defense;
        txtdata2.text = data.dexterity + "\n" + data.magicAttack + "\n" + data.magicDefense + "\n" + data.attackRange;

        string skilltext = "";

        for (int i = 0; i < skilldata.Count; i++)
        {
            var strb = new System.Text.StringBuilder(skilldata[i].description);
            for (int j = 0; skilldata[i].description.Length - letterPerLine * j > letterPerLine; j++)
            {
                strb.Insert((7 + letterPerLine) * j + letterPerLine, "\n\u3000\u3000\u3000\u3000\u3000\u3000");
            }
            skilldata[i].description = strb.ToString();
            skilltext += skilldata[i].name.PadRight(6, '\u3000') + skilldata[i].description + "\n";
        }
        skill.text = "<size=22>" + skilltext + "</size>";
    }
Beispiel #42
0
        public static void Main(string[] args)
        {
            var builder = new System.Text.StringBuilder("Hello World!");

            /*
             * builder.Append('-', 10);
             * builder.AppendLine();
             * builder.Append("Header");
             * builder.AppendLine();
             * builder.Append('-', 10);
             */
            //above is the same as chaining below
            builder
            .Append('-', 10)
            .AppendLine()
            .Append("Header")
            .AppendLine()
            .Append('-', 10);

            builder.Replace('-', '+');

            builder.Remove(0, 10);

            builder.Insert(0, new string('-', 10));

            Console.WriteLine(builder);

            Console.WriteLine("First char: " + builder[0]);
        }
Beispiel #43
0
        private static string ToUnsignedBase32String(long Value)
        {
            if (Value < 0)
            {
                throw new NotImplementedException();
            }

            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            long last = Value;

            while (last > 0)
            {
                int  i = (int)(last % 32);
                char c = ToBase32Char(i);
                builder.Insert(0, c);

                last = (long)(last / 32);
            }

            if (builder.Length == 0)
            {
                return("0");
            }
            else
            {
                return(builder.ToString());
            }
        }
Beispiel #44
0
        static void Main(string[] args)
        {
            var builder = new System.Text.StringBuilder("Hello World");

            builder.Append('-', 10);
            builder.AppendLine();
            builder.Append("Header");
            builder.AppendLine();
            builder.Append('-', 10);

            // Or because Append returns type StringBuilder method can be chained together
            //builder.Append('-', 10)
            //       .AppendLine()
            //       .Append("Header")
            //       .AppendLine()
            //       .Append('-', 10);


            // The following methods can also be chained together as well.
            builder.Replace('-', '+');

            builder.Remove(0, 10);

            builder.Insert(0, new string('-', 10));

            Console.WriteLine(builder);

            // Can access StringBuilder just like array or string
            Console.WriteLine("First Char: " + builder[0]);
        }
    public void OnEnable()
    {
        string name = "boss";

        if (characterReader == null)
        {
            characterReader = GameObject.FindObjectOfType <GameManager>().GetComponent <GameManager>().characterReader;
        }
        skilldata   = characterReader.GetMonsterSkillUI(name);
        description = characterReader.GetCharacterDescription(PawnType.Monster, name);

        //txtname.text="Andre";
        string skilltext = "";

        for (int i = 0; i < 5; i++)
        {
            var strb = new System.Text.StringBuilder(skilldata[i].description);
            for (int j = 0; skilldata[i].description.Length - 18 * j > 18; j++)
            {
                strb.Insert(25 * j + 18, "\n\u3000\u3000\u3000\u3000\u3000\u3000");
            }
            skilldata[i].description = strb.ToString();
            skilltext += skilldata[i].name.PadRight(6, '\u3000') + skilldata[i].description + "\n";
        }
        skill.text = "<size=22>" + skilltext + "</size>";
        story.text = "<size=22>" + description.story + "</size>";
        race.text  = description.race;
        story.text = description.story;
        desc.text  = description.description;
        index      = 0;
        UpdateImage();
    }
Beispiel #46
0
    private void StrContains_NewLine_null()
    {
        using (SerialPort com1 = TCSupport.InitFirstSerialPort())
            using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
            {
                Random rndGen = new Random(-55);
                System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE,
                                                                                            TCSupport.CharacterOptions.None);

                string newLine = "\0";

                Debug.WriteLine(
                    "Verifying write method with a NewLine=\\0 string and writing a string that contains the NewLine");

                com1.NewLine = newLine;
                com1.Open();

                if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
                {
                    com2.Open();
                }

                strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine);

                VerifyWriteLine(com1, com2, strBldrToWrite.ToString());
            }
    }
Beispiel #47
0
    /// <summary>
    /// 整理文字。确保首字母不出现标点
    /// </summary>
    /// <param name="_component">text组件</param>
    /// <param name="_text">需要填入text中的内容</param>
    /// <returns></returns>
    public IEnumerator MClearUpExplainMode(Text _component, string _text)
    {
        _component.text = _text;

        //如果直接执行下边方法的话,那么_component.cachedTextGenerator.lines将会获取的是之前text中的内容,而不是_text的内容,所以需要等待一下
        yield return(new WaitForSeconds(0.001f));

        MExpalinTextLine = _component.cachedTextGenerator.lines;

        //需要改变的字符序号
        int mChangeIndex = -1;

        MExplainText = new System.Text.StringBuilder(_component.text);

        for (int i = 1; i < MExpalinTextLine.Count; i++)
        {
            //首位是否有标点
            bool _b = Regex.IsMatch(_component.text[MExpalinTextLine[i].startCharIdx].ToString(), strRegex);

            if (_b)
            {
                mChangeIndex = MExpalinTextLine[i].startCharIdx - 1;

                MExplainText.Insert(mChangeIndex, "\n");
            }
        }

        _component.text = MExplainText.ToString();

        //_component.text = _text;
    }
Beispiel #48
0
    public bool StrContains_NewLine_null()
    {
        SerialPort com1   = TCSupport.InitFirstSerialPort();
        SerialPort com2   = TCSupport.InitSecondSerialPort(com1);
        Random     rndGen = new Random(-55);

        System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE, TCSupport.CharacterOptions.None);
        bool   retValue = true;
        string newLine  = "\0";

        Console.WriteLine("Verifying write method with a NewLine=\\0 string and writing a string that contains the NewLine");

        com1.NewLine = newLine;
        com1.Open();

        if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
        {
            com2.Open();
        }

        strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine);

        if (!VerifyWriteLine(com1, com2, strBldrToWrite.ToString()))
        {
            Console.Write("Err_011!!! Verifying write method with a NewLine=\\0 string and writing a string that contains the NewLine FAILED");
            retValue = false;
        }

        return(retValue);
    }
Beispiel #49
0
        /// <summary>
        /// Converts a number to System.String.
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static System.String ToString(long number)
        {
            System.Text.StringBuilder s = new System.Text.StringBuilder();

            if (number == 0)
            {
                s.Append("0");
            }
            else
            {
                if (number < 0)
                {
                    s.Append("-");
                    number = -number;
                }

                while (number > 0)
                {
                    char c = digits[(int)number % 36];
                    s.Insert(0, c);
                    number = number / 36;
                }
            }

            return(s.ToString());
        }
Beispiel #50
0
    //写一个单元格
    public static void Write(string value)
    {
        int  beginIdx     = s_buff.Length;
        bool isNeedQuotes = false;//需要用引号括起来

        for (int i = 0; i < value.Length; ++i)
        {
            if (isNeedQuotes == false && (value[i] == ',' || value[i] == '\r' || value[i] == '\n' || value[i] == '"'))
            {
                isNeedQuotes = true;
            }

            if (value[i] == '"')
            {
                s_buff.Append('"');
            }

            s_buff.Append(value[i]);
        }

        if (isNeedQuotes)
        {
            s_buff.Insert(beginIdx, '"');
            s_buff.Append('"');
        }
    }
Beispiel #51
0
        /// <summary>
        /// 将cshtml的Web形式路径转换为类名
        /// </summary>
        /// <param name="razorFileWebPath">Web路径形式</param>
        /// <returns></returns>
        public static string RazorPathToClassName(string razorFileWebPath)
        {
            var  builder       = new System.Text.StringBuilder();
            bool isNumberFirst = false;

            foreach (byte b in Encoding.UTF8.GetBytes(razorFileWebPath))
            {
                if (b >= (byte)'0' && b <= (byte)'9')
                {
                    if (builder.Length == 0)
                    {
                        isNumberFirst = true;
                    }
                    builder.Append((char)b);
                }
                else if (b >= (byte)'a' && b <= (byte)'z')
                {
                    builder.Append((char)b);
                }
                else if (b >= (byte)'A' && b <= (byte)'Z')
                {
                    builder.Append((char)b);
                }
                else
                {
                    builder.Append("_");
                }
            }
            if (isNumberFirst)
            {
                builder.Insert(0, "_");
            }
            return(builder.ToString());
        }
Beispiel #52
0
        public static void AddTwoCriteria(
            ref System.Text.StringBuilder Criteria,
            string SecondCriteria,
            bool IsAnd)
        {
            string strJoin = "";

            if (IsAnd)
            {            //AND 连接
                strJoin = " AND ";
            }
            else
            {
                strJoin = " OR ";
            }

            if (SecondCriteria.Trim() == string.Empty)
            {
                return;
            }

            if (Criteria.ToString().Trim() != string.Empty)
            {
                Criteria.Append(strJoin);
            }

            Criteria.Append("(" + SecondCriteria.Trim() + ")");
            Criteria.Insert(0, "(");
            Criteria.Append(")");
        }
Beispiel #53
0
    public void UpdateAdventurer()
    {
        type = adventurerPage.adventurerList[adventurerPage.currentid];
        string name = type.ToString();

        skilldata   = characterReader.GetEnemySkillUI(name);
        description = characterReader.GetCharacterDescription(PawnType.Enemy, name);

        txtname.text = name;
        string skilltext = "";

        for (int i = 0; i < skilldata.Count; i++)
        {
            var strb = new System.Text.StringBuilder(skilldata[i].description);
            for (int j = 0; skilldata[i].description.Length - 18 * j > 18; j++)
            {
                strb.Insert(25 * j + 18, "\n\u3000\u3000\u3000\u3000\u3000\u3000");
            }
            skilldata[i].description = strb.ToString();
            skilltext += skilldata[i].name.PadRight(6, '\u3000') + skilldata[i].description + "\n";
        }
        skill.text = skilltext;
        story.text = description.story;
        race.text  = description.race;
        desc.text  = description.description;

        if ((sprite = Resources.Load("Image/character/" + name, typeof(Sprite)) as Sprite) != null)
        {
            image.sprite = sprite;
        }
    }
Beispiel #54
0
        static void Main(string[] args)
        {
            string inputString = Console.ReadLine();

            string[] command = Console.ReadLine().Split(' ').ToArray();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(inputString);

            switch (command[0])
            {
            case "Remove":
                sb.Remove(int.Parse(command[1]), int.Parse(command[2]));
                break;

            case "Insert":
                sb.Insert(int.Parse(command[1]), command[2]);
                break;

            case "Replace":
                sb.Replace(command[1], command[2]);
                break;

            case "Append":
                sb.Append(command[1]);
                break;
            }

            Console.WriteLine(sb);
        }
Beispiel #55
0
 string GetPathName(Transform t)
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     sb.Append(t.gameObject.name);
     while (t != activeGO.transform)
     {
         t = t.parent;
         if (t == null)
         {
             break;
         }
         sb.Insert(0, ":");
         sb.Insert(0, t.gameObject.name);
     }
     return(sb.ToString());
 }
Beispiel #56
0
        static void Main(string[] args)
        {
            //Declare & initializes a StringBuilder object sb, and append a string later
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            //Declare & initializes a StringBuilder object sb, and append a string in the same statement
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder("Hello World!!");

            //Declare & initializes a StringBuilder object sb, and append a string in the same statement,
            //and define the max capacity which is here is 70 char.
            System.Text.StringBuilder sb2 = new System.Text.StringBuilder("Hello World!!", 70);

            Console.WriteLine("_1-------------------------------------------------------------");
            //Add or append a string to StringBuilder.
            sb.Append("Hello");
            //Add or append a string to StringBuilder with a newline at the end.
            sb.AppendLine(" World!!");
            sb.AppendLine("This is new line.");
            Console.WriteLine(sb);

            Console.WriteLine("_2-------------------------------------------------------------");
            //Format input string into specified format and then append it.
            System.Text.StringBuilder amountMsg = new System.Text.StringBuilder("Your total amount is ");
            amountMsg.AppendFormat("{0:C} ", 25);

            Console.WriteLine(amountMsg);

            Console.WriteLine("_3-------------------------------------------------------------");
            //Inserts the string at specified index in StringBuilder.
            sb1.Insert(5, " C#");

            Console.WriteLine(sb1);

            Console.WriteLine("_4-------------------------------------------------------------");
            //Replaces all occurance of a specified string with a specified replacement string.
            sb1.Replace("C#", "JavaScript ");

            Console.WriteLine(sb1);

            Console.WriteLine("_5-------------------------------------------------------------");
            //Removes the string at specified index with specified length.
            sb1.Remove(6, 10);

            Console.WriteLine(sb1);

            Console.WriteLine("_6-------------------------------------------------------------");
            //Uses indexer to get all the characters of StringBuilder using for loop.
            for (int i = 0; i < sb1.Length; i++)
            {
                Console.Write(sb1[i]);
            }

            Console.WriteLine("");
            Console.WriteLine("_7-------------------------------------------------------------");
            //Use ToString() method to get string from StringBuilder.
            string str = sb1.ToString();

            Console.WriteLine(str);
        }
    /**
     * Print out the full path in "Game Object/Child" format
     */
    private static string FullPath(Transform transform)
    {
        var sb = new System.Text.StringBuilder();

        while (transform != null)
        {
            sb.Insert(0, transform.name);
            transform = transform.parent;

            if (transform != null)
            {
                sb.Insert(0, '/');
            }
        }

        return(sb.ToString());
    }
Beispiel #58
0
        /// <summary>
        /// 履歴カテゴリ選択テーブル作成
        /// </summary>
        protected void CreateHistoryCategoryDatatable(int intHistoryRow, int intItemRow, string Type, DataTable dt)
        {
            BuisinessLogic.BLTroubleList bLogic = new BuisinessLogic.BLTroubleList();
            DataTable dtCategoryName            = null;
            String    strCategoryName           = "";

            string[] stArrayData = ((System.Data.DataTable)(ViewState[Def.DefHISTORY])).Rows[intHistoryRow].ItemArray[intItemRow].ToString().Split(',');

            foreach (String stData in stArrayData)
            {
                if (!String.IsNullOrEmpty(stData))
                {
                    dtCategoryName = bLogic.GetCategoryName(Type, stData);
                    if (dtCategoryName.Rows.Count > 0)
                    {
                        strCategoryName = dtCategoryName.Rows[0].ItemArray[0].ToString();
                    }

                    DataRow dr = dt.NewRow();
                    dr["TableType"] = Type;
                    if (intItemRow == Def.DefSEARCH_PARTS_N)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder(stData);
                        //カンマを挿入する
                        sb.Insert(2, ",");
                        sb.Insert(5, ",");
                        string strWork = sb.ToString();
                        dr["ItemValue1"] = strWork + "," + strCategoryName;
                    }
                    else if (intItemRow == Def.DefSEARCH_PARTS_S)
                    {
                        dr["ItemValue1"] = stData + ",,," + strCategoryName;
                    }
                    else if (intItemRow == Def.DefSEARCH_BUSYO || intItemRow == Def.DefSEARCH_HYOUKA)
                    {
                        dr["ItemValue1"] = stData;
                    }
                    else
                    {
                        dr["ItemValue1"] = stData + "," + strCategoryName;
                    }
                    dt.Rows.Add(dr);    //行追加
                }
            }
        }
Beispiel #59
0
 public Bag(string s)
 {
     Char[] chars = s.ToLower().ToCharArray();
     Array.Sort(chars);
     Char[] letters = Array.FindAll <char>(chars, Char.IsLetter);
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     sb.Insert(0, letters);
     guts = sb.ToString();
 }
Beispiel #60
0
    private string RunCommand(string command)
    {
        string[] words = command.Trim().Split(' ');

        if (words[0] == "?")
        {
            // show help
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            // @TODO: Fixed width font
            foreach (string declarer in declarers)
            {
                string title = string.Format("\nClass: {0}\n", declarer);
                sb.Append(title);
                sb.Insert(sb.Length, "=", title.Length - 1);
                sb.Append("\n");
                foreach (GEConsoleCommand cmd in commands)
                {
                    if (cmd.declaringClass != declarer)
                    {
                        continue;
                    }
                    string shortForm = "";
                    if (cmd.names.Length == 2)
                    {
                        shortForm = cmd.names[1];
                    }
                    string[] helpLines = new string[] { "" };
                    if (cmd.help != null)
                    {
                        helpLines = cmd.help.Split('\n');
                    }
                    // offset any remaining help lines past command and short-cut columns
                    sb.Append(string.Format("{0,20}  {1,5}   {2}\n", cmd.names[0], shortForm, helpLines[0]));
                    if (helpLines.Length > 1)
                    {
                        for (int i = 1; i < helpLines.Length; i++)
                        {
                            sb.Append(string.Format("                             {0}\n", helpLines[i]));
                        }
                    }
                }
            }
            return(sb.ToString());
        }

        foreach (GEConsoleCommand cmd in commands)
        {
            foreach (string name in cmd.names)
            {
                if (name == words[0])
                {
                    return(cmd.Run(words));
                }
            }
        }
        return(string.Format("Unknown command :{0}:\n ? for help", words[0]));
    }