当前位置: 首页>>代码示例>>C#>>正文


C# StringBuilder类代码示例

本文整理汇总了C#中StringBuilder的典型用法代码示例。如果您正苦于以下问题:C# StringBuilder类的具体用法?C# StringBuilder怎么用?C# StringBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


StringBuilder类属于命名空间,在下文中一共展示了StringBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        public static void Main()
        {
            #if DEBUG
            Console.SetIn(new System.IO.StreamReader(@"../../test.020.in.txt"));
            Debug.Listeners.Add(new ConsoleTraceListener());
            #endif

            Stopwatch sw = new Stopwatch();
            sw.Start();
            StringBuilder sb = new StringBuilder();
            int lines = int.Parse(Console.ReadLine());
            for (int i = 0; i < lines; i++)
            {
                string line = Console.ReadLine();

                bool isValid = Validate(line);
                if (isValid)
                {
                    sb.AppendLine("VALID");
                }
                else
                {
                    sb.AppendLine("INVALID");
                }
            }
            sw.Stop();
            Console.Write(sb.ToString());
            Debug.WriteLine(sw.Elapsed);
            string bla = "asdlj";
        }
开发者ID:vanndann,项目名称:TelerikAcademy,代码行数:30,代码来源:Program.cs

示例2: ComposeSentence

        public string ComposeSentence(string[] words)
        {
            StringBuilder text = new StringBuilder();
            bool hasSpace = true;

            for (int i = 0; i < words.Length; i++)
            {
                if (IsNoSpacePunctuation(words[i])) text.Append(words[i]);
                else if (IsReverseSpacePunctuation(words[i]))
                {
                    hasSpace = false;
                    text.Append(" " + words[i]);
                }
                else if (i == 0)
                {
                    text.Append(StaticHelper.FirstLetterToUpper(words[i]));
                }
                else
                {
                    if (words[i - 1] == ".") words[i] = StaticHelper.FirstLetterToUpper(words[i]);

                    if (hasSpace) text.Append(" " + words[i]);
                    else text.Append(words[i]);
                    hasSpace = true;
                }
            }

            string newText = text.ToString().Trim();
            return newText;
        }
开发者ID:Shoop123,项目名称:Reworder-C-Sharp,代码行数:30,代码来源:Composer.cs

示例3: FormatMessage

		internal static string FormatMessage (string msg)
		{
			StringBuilder sb = new StringBuilder ();
			bool wasWs = false;
			foreach (char ch in msg) {
				if (ch == ' ' || ch == '\t') {
					if (!wasWs)
						sb.Append (' ');
					wasWs = true;
					continue;
				}
				wasWs = false;
				sb.Append (ch);
			}

			var doc = TextDocument.CreateImmutableDocument (sb.ToString());
			foreach (var line in doc.Lines) {
				string text = doc.GetTextAt (line.Offset, line.Length).Trim ();
				int idx = text.IndexOf (':');
				if (text.StartsWith ("*", StringComparison.Ordinal) && idx >= 0 && idx < text.Length - 1) {
					int offset = line.EndOffsetIncludingDelimiter;
					msg = text.Substring (idx + 1) + doc.GetTextAt (offset, doc.TextLength - offset);
					break;
				}
			}
			return msg.TrimStart (' ', '\t');
		}
开发者ID:sushihangover,项目名称:monodevelop,代码行数:27,代码来源:Revision.cs

示例4: SerializeObject

        private string SerializeObject(object obj, int depth)
        {
            var type = obj.GetType();
            if (!IsSerializeableType(obj) && !(obj is string))
            {
                return null;
            }
            StringBuilder stringBuilder = new StringBuilder();


            var fieldInfos = type.GetFields();
            stringBuilder.Append("{\n");
            foreach (var fieldInfo in fieldInfos)
            {
                var attributes = fieldInfo.GetCustomAttributes();

                if (attributes.OfType<NonSerializedAttribute>().Any())
                {
                    continue;
                }
                var value = fieldInfo.GetValue(obj);
                stringBuilder.Append(SerializeString(fieldInfo.Name, depth + 1));
                stringBuilder.Append(" : ");
                if (IsSimpleType(value))
                {
                    stringBuilder.Append(SerializeByDepth(value, 0) + "\n");
                    continue;
                }
                stringBuilder.Append(SerializeByDepth(value, depth + 1) + "\n");
            }
            stringBuilder.Append(GetTabs(depth) + "}");
            return stringBuilder.ToString();
        }
开发者ID:sirgl,项目名称:json-serializer-dotnet,代码行数:33,代码来源:JsonSerializer.cs

示例5: FormatMethod

 protected virtual string FormatMethod(MethodBase method)
 {
     var sb = new StringBuilder();
     if (method.DeclaringType != null)
     {
         sb.Append(method.DeclaringType.FullName);
         sb.Append(".");
     }
     sb.Append(method.Name);
     if (method.IsGenericMethod)
     {
         sb.Append("<");
         sb.Append(string.Join(", ", method.GetGenericArguments().Select(t => t.Name)));
         sb.Append(">");
     }
     sb.Append("(");
     var f = false;
     foreach (var p in method.GetParameters())
     {
         if (f) sb.Append(", ");
         else f = true;
         sb.Append(p.ParameterType.Name);
         sb.Append(' ');
         sb.Append(p.Name);
     }
     sb.Append(")");
     return sb.ToString();
 }
开发者ID:darilek,项目名称:dotvvm,代码行数:28,代码来源:ExceptionSectionFormatter.cs

示例6: ToCSharpString

		private static void ToCSharpString(Type type, StringBuilder name)
		{
			if (type.IsArray)
			{
				var elementType = type.GetElementType();
				ToCSharpString(elementType, name);
				name.Append(type.Name.Substring(elementType.Name.Length));
				return;
			}
			if (type.IsGenericParameter)
			{
				//NOTE: this has to go before type.IsNested because nested generic type is also a generic parameter and otherwise we'd have stack overflow
				name.AppendFormat("·{0}·", type.Name);
				return;
			}
			if (type.IsNested)
			{
				ToCSharpString(type.DeclaringType, name);
				name.Append(".");
			}
			if (type.IsGenericType == false)
			{
				name.Append(type.Name);
				return;
			}
			name.Append(type.Name.Split('`')[0]);
			AppendGenericParameters(name, type.GetGenericArguments());
		}
开发者ID:CV1,项目名称:Windsor,代码行数:28,代码来源:TypeUtil.cs

示例7: Main

        static void Main()
        {
            string inputStr = Console.ReadLine();
            string multipleString = "";
            while (inputStr != "END")
            {
                multipleString += inputStr;
                inputStr = Console.ReadLine();
            }
            string pattern = @"(?<=<a).*?\s*href\s*=\s*((""[^""]*""(?=>))|('[^']*'(?=>))|([\w\/\:\.]+\.\w{3})|(\/[^'""]*?(?=>)))";
               //string pattern = @"(?s)(?:<a)(?:[\s\n_0-9a-zA-Z=""()]*?.*?)(?:href([\s\n]*)?=(?:['""\s\n]*)?)([a-zA-Z:#\/._\-0-9!?=^+]*(\([""'a-zA-Z\s.()0-9]*\))?)(?:[\s\na-zA-Z=""()0-9]*.*?)?(?:\>)";
            MatchCollection collection = Regex.Matches(multipleString, pattern);
            List<string> resultStrings = new List<string>();
            foreach (Match match in collection)
            {
                StringBuilder tempStr = new StringBuilder(match.Groups[2].Value);
                if (tempStr[0] == '"' || tempStr[0] == '\'')
                {
                    tempStr.Remove(0,1);
                }
                if (tempStr[tempStr.Length-1] == '"' || tempStr[tempStr.Length-1] == '\'')
                {
                    tempStr.Remove(tempStr.Length-1,1);
                }
                resultStrings.Add(tempStr.ToString());
                Console.WriteLine(tempStr);

            }
            //Console.WriteLine(string.Join("\r\n",resultStrings));
        }
开发者ID:exploitx3,项目名称:C-Sharp-,代码行数:30,代码来源:Extract+Hyperlinks.cs

示例8: Page_Load

 protected void Page_Load(object sender, EventArgs e)
 {
     IUnityContainer container = new UnityContainer();
     UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
     section.Configure(container);
     if (Request["installation"] != null)
     {
         int installationid = Int32.Parse(Request["installation"]);
         userid = Int32.Parse(Request["userid"]);
         user = Request["user"];
         sservice = container.Resolve<IStatisticService>();
         IInstallationBL iinstall = container.Resolve<IInstallationBL>();
         imodel = iinstall.getInstallation(installationid);
         Dictionary<InstallationModel, List<InstallationState>> statelist = sservice.getInstallationState(imodel.customerid);
         StringBuilder str = new StringBuilder();
         str.Append("<table border = '1'><tr><th>Description</th><th>Messwert</th><th>Einheit</th></tr>");
         foreach (var values in statelist)
         {
             if(values.Key.installationid.Equals(installationid))
             {
                 foreach (var item in values.Value)
                 {
                      str.Append("<tr><td>" + item.description + "</td><td>" + item.lastValue + "</td><td>" + item.unit + "</td></tr>");
                 }
                 break;
             }
         }
         str.Append("</table>");
         anlagenzustand.InnerHtml = str.ToString();
     }
 }
开发者ID:daniel9992000,项目名称:bif5-sks-csharp,代码行数:31,代码来源:InstallationDetail.aspx.cs

示例9: Encode

        public static string Encode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] bytes = Encoding.UTF8.GetBytes(str);

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);

            stream2.FlushFinalBlock();

            StringBuilder builder = new StringBuilder();

            foreach (byte num in stream.ToArray())
            {

                builder.AppendFormat("{0:X2}", num);

            }

            stream.Close();

            return builder.ToString();
        }
开发者ID:MrNor,项目名称:WxMp,代码行数:31,代码来源:CryptHelper.cs

示例10: IsCardNumberValid

        /// <summary>
        /// Validates a credit card number using the standard Luhn/mod10 validation algorithm.
        /// </summary>
        /// <param name="cardNumber">Card number, with or without punctuation</param>
        /// <returns>
        /// 	<c>true</c> if card number appears valid; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsCardNumberValid(string cardNumber)
        {
            int i;

            var cleanNumber = new StringBuilder();
            for (i = 0; i < cardNumber.Length; i++)
                if (char.IsDigit(cardNumber, i))
                    cleanNumber.Append(cardNumber[i]);

            if (cleanNumber.Length < 13 || cleanNumber.Length > 16)
                return false;

            for (i = cleanNumber.Length + 1; i <= 16; i++)
                cleanNumber.Insert(0, "0");

            string number = cleanNumber.ToString();
            int total = 0;

            for (i = 1; i <= 16; i++)
            {
                int multiplier = 1 + (i % 2);
                int digit = int.Parse(number.Substring(i - 1, 1));
                int sum = digit * multiplier;
                
                if (sum > 9)
                    sum -= 9;

                total += sum;
            }
            return (total % 10 == 0);
        }
开发者ID:arpitgold,项目名称:Exceptionless,代码行数:38,代码来源:CreditCardValidation.cs

示例11: ByteArrayToString

        public string ByteArrayToString(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            byte[] newdata = new byte[3];

            // 2 bytes 3 characters
            // First, bits with weight 4,8,16,32,64 of byte 1
            // Second, bits with weight 32,64,128 of byte 2 plus bits with weight 1,2 from byte 1
            // Third, bits with  weight 1,2,4,8,16 of byte 2
            newdata[0] = (byte)(((int)data[0]& 0x7c)/4);
            newdata[1] = (byte)((((int)data[0] & 0x03)*8) + (((int)data[1] & 0xe0) / 32));
            newdata[2] = (byte)((int)data[1] & 0x1f);

            for (int i = 0; i < newdata.Length; i++)
            {
                if (newdata[i] >= 0x01 && newdata[i] <= 0x1a)
                    sb.Append(((char)((((int)newdata[i])) + 65 - 0x01)));
                else if (newdata[i] == 0x1b)
                    sb.Append('-');
                else if (newdata[i] == 0x00)
                    sb.Append(' ');
            }

            return sb.ToString();
        }
开发者ID:Fyrecrypts,项目名称:HiToText,代码行数:25,代码来源:explorer.cs

示例12: TopUsersThatLiked

        public void TopUsersThatLiked(StringBuilder builder)
        {
            var users = GetUsersThatLiked();
            if (users == null || users.Count == 0)
            {
                return;
            }
            var groupedUsers = users.GroupBy(x => x).Select(x => new { x.Key, Count = x.Count() }).OrderByDescending(x => x.Count).ToList();

            int to = 0;
            if (groupedUsers == null || groupedUsers.Count == 0)
            {
                return;

            }
            else if (groupedUsers.Count > 0 && groupedUsers.Count < 3)
            {
                to = groupedUsers.Count + 1;
            }
            else
            {
                to = 4;
            }

            builder.Append("top users that liked your links: ");
            mHtmlBuilder.For(1, to, i =>
                {
                    builder.Append(i);
                    builder.Append(". <strong>");
                    builder.Append(mQuerier.GetNameByFId(groupedUsers[i-1].Key.ToString()));
                    builder.Append("</strong> - <strong>");
                    builder.Append(groupedUsers[i - 1].Count);
                    builder.Append("</strong> times");
                });
        }
开发者ID:amityo,项目名称:MyFacebookLinks,代码行数:35,代码来源:StatisticsBuilder.cs

示例13: getPatient

 /// <summary>
 /// ดึงรายชื่อพนักงานตามเงื่อนไขที่กำหนด เพื่อนำไปแสดงบนหน้า ConvertByPayor
 /// </summary>
 /// <param name="doeFrom"></param>
 /// <param name="doeTo"></param>
 /// <param name="payor"></param>
 /// <returns></returns>
 public DataTable getPatient(DateTime doeFrom,DateTime doeTo,string payor,string mobileStatus)
 {
     System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
     #region Variable
     var dt = new DataTable();
     var strSQL = new StringBuilder();
     var clsSQL = new clsSQLNative();
     #endregion
     #region Procedure
     #region SQLQuery
     strSQL.Append("SELECT ");
     strSQL.Append("No,HN,PreName,Name,LastName,DOE,Payor,SyncWhen,'0' IsConvertPreOrder ");
     strSQL.Append("FROM ");
     strSQL.Append("Patient P ");
     strSQL.Append("WHERE ");
     strSQL.Append("(DOE BETWEEN '" + doeFrom.ToString("yyyy-MM-dd HH:mm") + "' AND '" + doeTo.ToString("yyyy-MM-dd HH:mm") + "') ");
     if(payor!="" && payor.ToLower() != "null")
     {
         strSQL.Append("AND Payor='"+payor+"' ");
     }
     if (mobileStatus == "NotRegister")
     {
         strSQL.Append("AND SyncStatus!='1' ");
     }
     else if (mobileStatus == "Register")
     {
         strSQL.Append("AND SyncStatus='1' ");
     }
     strSQL.Append("ORDER BY ");
     strSQL.Append("No;");
     #endregion
     dt = clsSQL.Bind(strSQL.ToString(), clsSQLNative.DBType.SQLServer, "MobieConnect");
     #endregion
     return dt;
 }
开发者ID:oofdui,项目名称:ContactCheckup-MassConvert,代码行数:42,代码来源:clsTempData.cs

示例14: BuildExceptionReport

        static StringBuilder BuildExceptionReport(Exception e, StringBuilder sb, int d)
        {
            if (e == null)
                return sb;

            sb.AppendFormat("Exception of type `{0}`: {1}", e.GetType().FullName, e.Message);

            var tle = e as TypeLoadException;
            if (tle != null)
            {
                sb.AppendLine();
                Indent(sb, d);
                sb.AppendFormat("TypeName=`{0}`", tle.TypeName);
            }
            else // TODO: more exception types
            {
            }

            if (e.InnerException != null)
            {
                sb.AppendLine();
                Indent(sb, d); sb.Append("Inner ");
                BuildExceptionReport(e.InnerException, sb, d + 1);
            }

            sb.AppendLine();
            Indent(sb, d); sb.Append(e.StackTrace);

            return sb;
        }
开发者ID:RobotCaleb,项目名称:OpenRA,代码行数:30,代码来源:Program.cs

示例15: GetAllCidades

        public static DataTable GetAllCidades(int estado_id)
        {
            DataTable retorno = new DataTable();
            StringBuilder SQL = new StringBuilder();
            SQL.Append(@"SELECT CidadeId, Nome FROM Cidade WHERE EstadoId = @ESTADO_ID");

            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Mendes_varejo"].ConnectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand(SQL.ToString(), connection);
                    command.Parameters.AddWithValue("@ESTADO_ID", estado_id);
                    command.ExecuteNonQuery();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(retorno);
                }
            }
            catch (Exception erro)
            {
                throw erro;
            }

            return retorno;
        }
开发者ID:clebermendes,项目名称:mendestec,代码行数:25,代码来源:FornecedorDAO.cs


注:本文中的StringBuilder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。