Home > OS >  If a string contains a double character change it to another string C#
If a string contains a double character change it to another string C#

Time:10-25

I created a Person Model:

Model Person = new Model();
Person.LastName = values[0];

[LastName is a string]
I would like to replace the values [0] which is "Anna" with another string value like "Frank" if it contains a double character, in this case "if Anna contains a double character, change the value with another string".

how to do?

CodePudding user response:

This could be achieved with easy extensions funciton for string:

public static class StringExntesions
{
    public static bool HasDoubleChar(this string @this)
    {
        for (int i = 1; i < @this.Length; i  )
        {
            if (@this[i] == @this[i - 1])
            {
                return true;
            }
        }
        return false;
    }
}

and then you could use it:

Person.LastName = values[0].HasDoubleChar()
    ? "Frank"
    : values[0];

CodePudding user response:

        public static string Do(string source, string replacement)
        {
            char c = source.ToLower()[0]; // do you care about case? E.g., Aaron.
            for(int i = 1; i < source.Length; i  )
            {
                if (source.ToLower()[i] == c)
                {
                    return replacement;
                }
            }
            return source;
        }

        public static void Main()
        {
            string thing = "Aaron";
            thing = Do(thing, "Frank");

        }
  • Related