Home > Software engineering >  I'm trying to insert a string into another string without using built-in functions
I'm trying to insert a string into another string without using built-in functions

Time:12-26

class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Your string: ");
            string str = Console.ReadLine();

            
            stringFuncs.Insert(str, "Hello", 5);

            
        }
    }

public static string SubString(string word,int a, int b)
        {

            for(int i = a; i < b; i  )
            {
                Console.Write(word[i]);//my substring method
            }
            return word;
        }
public static string Insert(string word, string subs, int index)
        {
            
            int numberOfLetters = 0;
            foreach (var c in word)
            {
                numberOfLetters  ;
            }

            
            Console.WriteLine(stringFuncs.SubString(word, 0, index)   subs   stringFuncs.SubString(word, index,numberOfLetters-index));
            return word;

          

        }

I'm getting this as output whenever i write something : My stringHello My string

my substring method is wrong how can i make it so it only takes the part i needed and returns it back?

CodePudding user response:

You can use my method (if you just need a substring method):

class Program
{
    static string CustomSubstring(string text, short startIndex, short indexInQuestion)
    {
        short i;
        for (i = startIndex; i < text.Length; i  ) ;
        StringBuilder Temp = new StringBuilder();
        //"StringBuilder.Append()" is faster than "string =string"
        //switch is faster than if
        switch (indexInQuestion < i)
        {
            case true:
                char[] C = text.ToArray();
                for (short j = startIndex; j <= indexInQuestion; j  )
                {
                    Temp.Append(C[j]);
                }
                break;
        }
        return Temp.ToString();
    }
    static void Main(string[] args)
    {
        Console.WriteLine(CustomSubstring("Merry Christmas", 6, 14));
        Console.ReadKey();
    }
}

Output: Christmas

  • Related