HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Finding the postion of a substring in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thesubstringpostionfindingstring

Problem

I am given two strings and return the position if in the larger string the smaller string is found. If not I am returning -1 for position. Any suggestions for improving my code.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Reverse
{
    class MainClass
    {
        static int IsFound (string stringOne, string stringTwo){
            int j = 0;
            int position = -1;
            int length = stringTwo.Length - stringOne.Length;
            for (int i = 0; i < length; i++) {
                if (stringOne [j] == stringTwo [i]) {
                    position = i;
                    while (stringOne [j] == stringTwo [i]) {
                        j++;
                        i++;
                        if (stringOne.Length == j) {
                            return position;
                        }
                    }
                    j = 0;
                    position = -1;
                } 
            }
            return position;
        }
        public static void Main (string[] args)
        {
            string stringOne = "charter";
            string stringTwo = "cstarchabsccharldmscharterfadgafga";
            int test = IsFound (stringOne, stringTwo);
            Console.WriteLine(test);
            string stringThree = "atfc";
            test = IsFound (stringThree, stringTwo);
            Console.WriteLine(test);
        }
    }
}

Solution

Small improvement here:

Your IsFound method is making an assumption that stringTwo is longer than stringOne. Might I suggest:

Math.Abs(stringOne.Length - stringTwo.Length)

This way length will never be negative and the for loop will always execute.

Context

StackExchange Code Review Q#101429, answer score: 4

Revisions (0)

No revisions yet.