Insert() public method

public Insert ( int index, bool value ) : StringBuilder
index int
value bool
return StringBuilder
        /// <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 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() : "";
        }
Beispiel #3
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 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());
        }
 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");
 }
Beispiel #6
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();
        }
        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 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();
		}
        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();
        }
Beispiel #10
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;
 }
Beispiel #11
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();
                }
            }
        }
Beispiel #12
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();
        }
 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());
 }
 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();
 }
        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();
        }
        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;
        }
        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);
        }
        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 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;
        }
        /// <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;
        }
        /// <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 #23
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");
        }
Beispiel #24
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();
        }
		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();
		}
        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();
        }
        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();
        }
        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]);
                }
                
            }
        }
		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 #30
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");
        }