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


C# StringBuilder.Trim方法代码示例

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


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

示例1: DoToWhereStatement

			/// <summary>
			/// Constructs a WHERE statements on this column for the given <paramref name="values"/>.
			/// </summary>
			/// <param name="context">The <see cref="IMansionContext"/>.</param>
			/// <param name="commandContext">The <see cref="QueryCommandContext"/>.</param>
			/// <param name="pair">The <see cref="TableColumnPair"/>.</param>
			/// <param name="values">The values on which to construct the where statement.</param>
			protected override void DoToWhereStatement(IMansionContext context, QueryCommandContext commandContext, TableColumnPair pair, IList<object> values)
			{
				// assemble the properties
				var buffer = new StringBuilder();
				foreach (var value in values)
					buffer.AppendFormat("@{0},", commandContext.Command.AddParameter(value));

				// append the query
				commandContext.QueryBuilder.AppendWhere(" [{0}].[id] IN ( SELECT [{1}].[id] FROM [{1}] WHERE [{1}].[name] = '{2}' AND [{1}].[value] IN ({3}) )", commandContext.QueryBuilder.RootTableName, pair.Table.Name, PropertyName, buffer.Trim());
			}
开发者ID:Erikvl87,项目名称:Premotion-Mansion,代码行数:17,代码来源:MultiValuePropertyTable.cs

示例2: GetComments

		string GetComments()
		{
			var sb = new StringBuilder ();

			foreach (var c in Lexer.Comments)
			{
				if (c.CommentType.HasFlag(Comment.Type.Documentation))
					sb.AppendLine(c.CommentText);
			}

			TrackerVariables.Comments.AddRange(Lexer.Comments);
			Lexer.Comments.Clear();

			sb.Trim ();

			if (sb.Length == 0)
				return string.Empty;

			// Overwrite only if comment is not 'ditto'
			if (sb.Length != 5 || sb.ToString().ToLowerInvariant() != "ditto")
				PreviousComment = sb;

			return PreviousComment.ToString();
		}
开发者ID:DinrusGroup,项目名称:DinrusIDE,代码行数:24,代码来源:Parser_Impl.cs

示例3: SplitCommandLine

        /// <summary>
        /// Splits a command line by spaces, keeping quoted text together
        /// </summary>
        public static IEnumerable<string> SplitCommandLine(string commandLine)
        {
            if (string.IsNullOrWhiteSpace(commandLine)) return Enumerable.Empty<string>();
            var args = new List<string>();
            StringBuilder sb = new StringBuilder(commandLine);
            sb.Trim();

            int argStart = 0;
            int lastQuote = -1;
            for (int i = 0; i < sb.Length; i++)
            {
                char current = sb[i];
                if (char.IsWhiteSpace(current))
                {
                    if (argStart == i)
                    {
                        // Leading argument whitespace
                        argStart++;
                        continue;
                    }
                    else if (argStart != lastQuote)
                    {
                        // Not in a quote, end of arg
                        args.Add(sb.ToString(argStart, i - argStart));
                        argStart = i + 1;
                        continue;
                    }
                }

                if (current == '"')
                {
                    if (lastQuote == -1)
                    {
                        if (argStart == i)
                        {
                            // Start of quote
                            lastQuote = i;
                            argStart = i;
                            continue;
                        }
                    }
                    else
                    {
                        // End of quote, trim out quotes
                        argStart++;
                        args.Add(sb.ToString(argStart, i - argStart));
                        lastQuote = -1;
                        argStart = i + 1;
                        continue;
                    }
                }
            }

            if (lastQuote != -1)
            {
                // Orphaned quote, move the argument start forward
                argStart++;
            }

            if (argStart < sb.Length)
            {
                args.Add(sb.ToString(argStart, sb.Length - argStart));
            }

            return args;
        }
开发者ID:JeremyKuhne,项目名称:XTask,代码行数:69,代码来源:Strings.cs

示例4: CheckForPostSemicolonComment

        /// <summary>
        /// Returns the pre- and post-declaration comment
        /// </summary>
        /// <returns></returns>
        string CheckForPostSemicolonComment()
        {
            if (t == null)
                return string.Empty;

            int ExpectedLine = t.Line;

            var ret = new StringBuilder ();

            int i=0;
            foreach (var c in Lexer.Comments)
            {
                if (c.CommentType.HasFlag(Comment.Type.Documentation))
                {
                    // Ignore ddoc comments made e.g. in int a /** ignored comment */, b,c;
                    // , whereas this method is called as t is the final semicolon
                    if (c.EndPosition <= t.Location)
                    {
                        i++;
                        Comments.Add(c);
                        continue;
                    }
                    else if (c.StartPosition.Line > ExpectedLine)
                        break;

                    ret.AppendLine(c.CommentText);
                }

                i++;
                Comments.Add(c);
            }
            Lexer.Comments.RemoveRange(0, i);

            if (ret.Length == 0)
                return string.Empty;

            ret.Trim();

            // Add post-declaration string if comment text is 'ditto'
            if (ret.Length == 5 && ret.ToString().ToLowerInvariant() == "ditto")
                return PreviousComment.ToString();

            // Append post-semicolon comment string to previously read comments
            if (PreviousComment.Length != 0) // If no previous comment given, do not insert a new-line
                return (PreviousComment = ret).ToString();

            ret.Insert (0, Environment.NewLine);

            PreviousComment.Append(ret.ToString());
            return ret.ToString();
        }
开发者ID:rainers,项目名称:D_Parser,代码行数:55,代码来源:Parser_Impl.cs

示例5: ParseSupportsRule

        // supports_rule
        //   : "@supports" supports_condition group_rule_body
        //   ;
        internal bool ParseSupportsRule(RuleAppendFunc aAppendFunc, object aProcessData)
        {
            bool conditionMet = false;
              var condition = new StringBuilder();

              mScanner.StartRecording();
              bool parsed = ParseSupportsCondition(ref conditionMet);

              if (!parsed) {
            mScanner.StopRecording();
            return false;
              }

              if (!ExpectSymbol('{', true)) {
            { if (!mSuppressErrors) mReporter.ReportUnexpected("PESupportsGroupRuleStart", mToken); };
            mScanner.StopRecording();
            return false;
              }

              UngetToken();
              mScanner.StopRecording(condition);

              // Remove the "{" that would follow the condition.
              if (condition.Length() != 0) {
            condition.Truncate(condition.Length() - 1);
              }

              // Remove spaces from the start and end of the recorded supports condition.
              condition.Trim(" ", true, true, false);

              // Record whether we are in a failing @supports, so that property parse
              // errors don't get reported.
              using (/*var failing = */new nsAutoFailingSupportsRule(this, conditionMet)) {

            GroupRule rule = new CSSSupportsRule(ref conditionMet, condition);
            return ParseGroupRule(rule, aAppendFunc, aProcessData);
              }
        }
开发者ID:jorik041,项目名称:CsCss,代码行数:41,代码来源:nsCSSParser.conv.cs

示例6: Format

        /// <summary>
        /// �������������� ������.
        /// <b>������������������!</b>
        /// </summary>
        /// <param name="txt">�������� �����.</param>
        /// <param name="smile">������� ��������� ���������.</param>
        /// <param name="doNotReplaceTags">�� �������� ��������� ������� HTML.</param>
        /// <param name="doNotFormatImplicitLinks">�� ������������� ���� �� ��������� ������.</param>
        /// <returns>���������������� �����.</returns>
        public virtual string Format(
            string txt,
            bool smile,
            bool doNotReplaceTags,
            bool doNotFormatImplicitLinks)
        {
            var sb = new StringBuilder(txt);

            sb.Trim(TrimArray);

            if (sb.IsEmpty())
                return "";

            // ��������! ������� �������������� �����.
            //

            // ������  ������������ ��������
            if (!doNotReplaceTags)
                sb = sb.ReplaceTagsWQ();

            // ���������� ���� ����� ������ ����� � \n
            //
            sb = _rxNewLineUnifier.Replace(sb, "\n");

            // ��������� �������� ����� � �����,
            // ������� �� ����� ���� ������ ����������.
            //

            // temporary remove [code...] tags
            const string codeExpression = "$$code{0}$$";
            var codeMatcher = new Matcher(codeExpression);
            sb = _rxCodeFormatting.Replace(sb, codeMatcher.Match);

            // temporary remove [img] tags
            const string imgExpression = "$$img{0}$$";
            var imgMatcher = new Matcher(imgExpression);
            sb = _imgTagRegex.Replace(sb, imgMatcher.Match);

            // temporary remove [url] & [purl] tags
            const string urlExpression = "$$url{0}$$";
            var urlMatcher = new Matcher(urlExpression);
            sb = _urlTagRegex.Replace(sb, urlMatcher.Match);

            // temporary remove implicit links
            const string implicitUrlExpression = "$$iurl{0}$$";
            var implicitUrlMatcher = new Matcher(implicitUrlExpression);
            if (!doNotFormatImplicitLinks)
                sb = _urlRegex.Replace(sb, implicitUrlMatcher.Match);

            // temporary remove [q] tags
            const string quoteExpression = "$$quote{0}$$";
            var quoteMatcher = new Matcher(quoteExpression);
            sb = _rxPrep12.Replace(sb, quoteMatcher.Match);

            // temporary remove [cut] tags
            const string cutExpression = "$$cut{0}$$";
            Matcher cutMatcher;
            do
            {
                cutMatcher = new Matcher(cutExpression);
                sb = _rxPrep13.Replace(sb, cutMatcher.Match);

                // �����������.
                sb = _rxTextUrl09.Replace(sb, "<span class='lineQuote'>$&</span>");

                // restore & transform [cut] tags
                for (var i = 0; i < cutMatcher.Count; i++)
                {
                    var m = cutMatcher[i];
                    var capt = String.IsNullOrEmpty(m.Groups[3].Value) ? "������� �����" : m.Groups[3].Value;
                    sb = sb.Replace(String.Format(cutExpression, i),
                        _hiddenTextSnippet.Replace("%CAPT%", capt).Replace("%TEXT%", m.Groups[4].Value).
                        Replace("%URL%", GetImagePrefix()));
                }
            } while (cutMatcher.Count > 0);

            // restore & transform [q] tags
            // ����������� [q].
            // http://www.rsdn.ru/forum/?mid=111506
            for (var i = 0; i < quoteMatcher.Count; i++)
                sb =
                    sb.Replace(
                        string.Format(quoteExpression, i),
                        string.Format(
                            "<blockquote class='q'><p>{0}</p></blockquote>",
                            quoteMatcher[i].Groups[1]));

            // ��������� ��������� � ������ ������ � http://www.rsdn.ru/forum/?mid=184751
            if (smile)
            {
                var prefix = GetImagePrefix();
//.........这里部分代码省略.........
开发者ID:CaptainFlint,项目名称:RsdnFormatter,代码行数:101,代码来源:TextFormatter.cs

示例7: TrimTest

 public void TrimTest()
 {
     StringBuilder sb = null;
     sb = new StringBuilder("   asd sdf  ");
     Assert.Equal(sb.Trim().ToString(), "asd sdf");
 }
开发者ID:donnieyoung,项目名称:osharp,代码行数:6,代码来源:StringBuilderExtensionsTest.cs

示例8: Format

		/// <summary>
		/// Форматирование текста.
		/// <b>НЕПОТОКОБЕЗОПАСНЫЙ!</b>
		/// </summary>
		/// <param name="txt">Исходный текст.</param>
		/// <param name="smile">Признак обработки смайликов.</param>
		/// <param name="doNotReplaceTags">Не заменять служебные символы HTML.</param>
		/// <param name="doNotFormatImplicitLinks">Не форматировать явно не указанные ссылки.</param>
		/// <returns>Сформатированный текст.</returns>
		public virtual string Format(
			string txt,
			bool smile,
			bool doNotReplaceTags,
			bool doNotFormatImplicitLinks)
		{
			var sb = new StringBuilder(txt);

			sb.Trim(TrimArray);

			if (sb.IsEmpty())
				return "";

			// Внимание! Порядок преобразования ВАЖЕН.
			//

			// Замена  небезопасных символов
			if (!doNotReplaceTags)
				sb = sb.ReplaceTagsWQ();

			// Приведение всех типов концов строк к \n
			//
			sb = _rxNewLineUnifier.Replace(sb, "\n");

			// Обработка исходных кодов и тегов, 
			// которые не могут быть внутри исходников.
			//

			// temporary remove [code...] tags
			const string codeExpression = "$$code{0}$$";
			var codeMatcher = new Matcher(codeExpression);
			sb = _rxCodeFormatting.Replace(sb, codeMatcher.Match);

			// temporary remove [img] tags
			const string imgExpression = "$$img{0}$$";
			var imgMatcher = new Matcher(imgExpression);
			sb = _imgTagRegex.Replace(sb, imgMatcher.Match);

			// temporary remove [url] & [purl] tags
			const string urlExpression = "$$url{0}$$";
			var urlMatcher = new Matcher(urlExpression);
			sb = _urlTagRegex.Replace(sb, urlMatcher.Match);

			// temporary remove implicit links
			const string implicitUrlExpression = "$$iurl{0}$$";
			var implicitUrlMatcher = new Matcher(implicitUrlExpression);
			if (!doNotFormatImplicitLinks)
				sb = _urlRegex.Replace(sb, implicitUrlMatcher.Match);

			// temporary remove [q] tags
			const string quoteExpression = "$$quote{0}$$";
			var quoteMatcher = new Matcher(quoteExpression);
			sb = _rxPrep12.Replace(sb, quoteMatcher.Match);

			// temporary remove [cut] tags
			const string cutExpression = "$$cut{0}$$";
			Matcher cutMatcher;
			do
			{
				cutMatcher = new Matcher(cutExpression);
				sb = _rxPrep13.Replace(sb, cutMatcher.Match);

				// Цитирование.
				sb = _rxTextUrl09.Replace(sb,
					m => $"<span class='lineQuote level{WebUtility.HtmlDecode(m.Groups["lev"].Value).Length}'>{m.Groups[0].Value}</span>");

				// restore & transform [cut] tags
				for (var i = 0; i < cutMatcher.Count; i++)
				{
					var m = cutMatcher[i];
					var capt = String.IsNullOrEmpty(m.Groups[3].Value) ? "Скрытый текст" : m.Groups[3].Value;
					sb = sb.Replace(String.Format(cutExpression, i),
						_hiddenTextSnippet.Replace("%CAPT%", capt).Replace("%TEXT%", m.Groups[4].Value).
						Replace("%URL%", GetImagePrefix()));
				}
			} while (cutMatcher.Count > 0);

			// restore & transform [q] tags
			// Цитирование [q].
			// http://www.rsdn.ru/forum/?mid=111506
			for (var i = 0; i < quoteMatcher.Count; i++)
				sb =
					sb.Replace(
						string.Format(quoteExpression, i),
						$"<blockquote class='q'><p>{quoteMatcher[i].Groups[1]}</p></blockquote>");

			// Обработка смайликов с учетом отмены и http://www.rsdn.ru/forum/?mid=184751
			if (smile)
			{
				var prefix = GetImagePrefix();
				sb = _smileReplacers.Aggregate(
//.........这里部分代码省略.........
开发者ID:rsdn,项目名称:RsdnFormatter,代码行数:101,代码来源:TextFormatter.cs

示例9: ClearComments

        public static string ClearComments(this string html)
        {
            html = html.CleanHeader();

            var starts = new List<int>();
            for (var i = 0; i < html.Length; i++)
            {
                if (i >= html.Length - 4)
                {
                    break;
                }

                i = html.IndexOf(@"<!--", i, StringComparison.Ordinal);
                if (i == -1)
                {
                    break;
                }
                starts.Add(i);
            }

            var ends = starts.Select(start => html.IndexOf(@"-->", start, StringComparison.Ordinal) + 3).ToList();

            var content = new StringBuilder(html).ToString(); 
            //Enable cleaning mso styling
            content = starts.Select((t, i) => html.Substring(t, ends[i] - t)).Aggregate(content, (current, comment) => current.Replace(comment, ""));

            content = content.Replace(@"<![if !vml]>", "");
            content = content.Replace(@"<![endif]>", "");




            content = content.Substring(content.IndexOf("<body"));
            content = content.Substring(content.IndexOf(">") + 1);
            content = content.Remove(content.LastIndexOf("</body>"), content.Length - content.LastIndexOf("</body>"));


            //deleting index from description
            if (content.Contains("<div style='mso-element:comment-list'>"))
            {
                content = content.Remove(content.IndexOf("<div style='mso-element:comment-list'>"));
            }

            for (int i = 0; ; i++)
            {
                if (!content.Contains(">["))
                {
                    break;
                }
                //content = content.Remove(content.IndexOf(">[")+1, 5);
                content = content.Remove(content.IndexOf(">[") + 1, (content.IndexOf("]</a>")+1) - (content.IndexOf(">[") + 1));
            }
            return content.Trim();

        }
开发者ID:nkravch,项目名称:SALMA-2.0,代码行数:55,代码来源:MarkupConverter.cs

示例10: TryCleanFilename

        /// <summary>
        /// Пытается очистить указанную строку, представляющую название файла (без пути), от недопустимых символов, если таковые присутствуют. 
        /// Если очистка успешна, возвращает 'true' и очищенное коректное имя файла через выводной параметр. 
        /// Если же указанную строку невозможно очистить, возвращает 'false' и NULL через выводной параметр.
        /// </summary>
        /// <param name="Input">Строка, представляющая имя файла без пути</param>
        /// <param name="FixedFilename">Выводной параметр, содержащий очищенное имя файла, если его удалось очистить</param>
        /// <returns></returns>
        public static Boolean TryCleanFilename(String Input, out String FixedFilename)
        {
            FixedFilename = null;
            if (Input.HasVisibleChars() == false) { return false; }
            StringBuilder sb = new StringBuilder(Input.Length);
            Char[] invalid_chars = Path.GetInvalidFileNameChars();
            foreach (Char current in Input)
            {
                if (current.IsIn(invalid_chars) == false)
                {
                    sb.Append(current);
                }
            }
            String output = sb.Trim().ToString();
            if (output.HasVisibleChars() == false) { return false; }

            String[] all_segments = output.Split(new char[1] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            String first_segment = all_segments.First();
            if (first_segment.IsIn(StringComparison.OrdinalIgnoreCase, FilePathTools.IllegalFilenames) == true)
            {
                if (all_segments.Length < 3) { return false; }
                else
                {
                    output = output.TrimStart(first_segment + ".", StringComparison.OrdinalIgnoreCase, false);
                }
            }
            FixedFilename = output;
            return true;
        }
开发者ID:Klotos,项目名称:KlotosLib,代码行数:37,代码来源:FilePathTools.cs

示例11: DoToWhereStatement

		/// <summary>
		/// Constructs a WHERE statements on this column for the given <paramref name="values"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="commandContext">The <see cref="QueryCommandContext"/>.</param>
		/// <param name="pair">The <see cref="TableColumnPair"/>.</param>
		/// <param name="values">The values on which to construct the where statement.</param>
		protected override void DoToWhereStatement(IMansionContext context, QueryCommandContext commandContext, TableColumnPair pair, IList<object> values)
		{
			// add the table to the query
			commandContext.QueryBuilder.AddTable(context, pair.Table, commandContext.Command);

			// check for single or multiple values
			if (values.Count == 1)
				commandContext.QueryBuilder.AppendWhere(" [{0}].[{1}] = @{2}", pair.Table.Name, pair.Column.ColumnName, commandContext.Command.AddParameter(GetValue(context, values[0])));
			else
			{
				// start the clause
				var buffer = new StringBuilder();
				buffer.AppendFormat("[{0}].[{1}] IN (", pair.Table.Name, pair.Column.ColumnName);

				// loop through all the values
				foreach (var value in values.Select(val => GetValue(context, val)))
					buffer.AppendFormat("@{0},", commandContext.Command.AddParameter(value));

				// finish the clause
				commandContext.QueryBuilder.AppendWhere("{0})", buffer.Trim());
			}
		}
开发者ID:Erikvl87,项目名称:Premotion-Mansion,代码行数:29,代码来源:PropertyColumn.cs

示例12: CleanIdentifier

 public static string CleanIdentifier(string input) {
     var sb = new StringBuilder(Regex.Replace(input, CLEAN_PATTERN, "_"));
     sb.Push(c => c.Equals('_') || Char.IsNumber(c));
     sb.Trim(" ");
     var result = sb.ToString();
     if (result.Equals(String.Empty) || result.All(c => c.Equals('_') || Char.IsNumber(c))) {
         result = "I" + input.GetHashCode().ToString(CultureInfo.InvariantCulture).Replace("-", "0");
     }
     if (!input.Equals(result)) {
         //logger.Debug("Using '{0}' to identify field '{1}'.", result, input);
     }
     return sb.ToString();
 }
开发者ID:modulexcite,项目名称:Transformalize,代码行数:13,代码来源:Common.cs


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