开发者

How can I ensure my c# string ends in a period?

开发者 https://www.devze.com 2023-03-31 10:06 出处:网络
I have c# strings looking like this: \"abc\"; \"def.\"; When I read these into another variable I need some simple way to check the l开发者_运维问答ast character of the string and if it\'s not a pe

I have c# strings looking like this:

"abc";
"def.";

When I read these into another variable I need some simple way to check the l开发者_运维问答ast character of the string and if it's not a period then append a period to that string.

Does anyone have any ideas of a simple way I could do this?


if (!str.EndsWith(".")) str += ".";

Is there a reason you can't do this a different way, though?


namespace ExtensionMethods
{
    public static class StringExtensionMethods
    {
        public static string EnsureEndsWithDot(this string str)
        {
            if (!str.EndsWith(".")) return str + ".";
            return str;
        }
    }
}


using System;

namespace StackoverflowConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
          Console.WriteLine(StringExtensionMethods.EnsureEndsWithDot("abc"));
        }
    }
}
namespace StackoverflowConsoleApp
{

    /// <summary>
    /// This class contains string extensions
    /// </summary>
    public static class StringExtensionMethods
    {
        /// <summary>
        /// constant dot
        /// </summary>
        private const string dot = ".";

        /// <summary>
        /// Ensures the string ends with dot character
        /// </summary>
        /// <param name="text"><see cref="string"/>Takes a string parameter</param>
        /// <returns><see cref="string"/>returns a string parameter</returns>
        public static string EnsureEndsWithDot(this string text)
        {
            if (!text.EndsWith(dot))
            {
                return string.Format("{0}{1}", text, dot);
            }

            return text;
        }
    }
}


This ought to do...

// Appends a ., or if myString was empty to begin with, makes it "."
myString = (myString != null && myString.Length != 0 && myString[myString.Length - 1] == '.') ? myString : (myString ?? "") + ".";
0

精彩评论

暂无评论...
验证码 换一张
取 消