I have tried to program a tic tac toe game in C# (with the help of tutorials). Overall it seems to be working fine (although the amount of code seems very excessive so sorry for that) but there appears to be one problem: Say, player 1 decides on row 1, column 1 and player 2 does the same afterwards, then player 2 overwrites player 1.
So far, this is the code:
namespace TicTacToe
{
class Program
{
static int turns = 1;
static char[] board =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
static char playerSignature = 'X';
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game. Enter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
DrawBoard(board);
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
DrawBoard(board);
}
}
private static void PlayAgain()
{
Console.WriteLine("Play again? y/n");
string playagain = Console.ReadLine();
switch (playagain)
{
case "n":
Console.WriteLine("Thanks for playing!");
Console.Clear();
break;
case "y":
Console.Clear();
ResetBoard();
break;
}
}
private static void DrawBoard(char[] board)
{
string row = "| {0} | {1} | {2} |";
string sep = "|___|___|___|";
Console.WriteLine(" ___ ___ ___ ");
Console.WriteLine(row, board[0], board[1], board[2]);
Console.WriteLine(sep);
Console.WriteLine(row, board[3], board[4], board[5]);
Console.WriteLine(sep);
Console.WriteLine(row, board[6], board[7], board[8]);
Console.WriteLine(sep);
}
private static void ResetBoard()
{
char[] newBoard =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
board = newBoard;
DrawBoard(board);
turns = 0;
}
private static void Draw()
{
Console.WriteLine("It's a draw!\n" +
"Press any key to play again.");
Console.ReadKey();
ResetBoard();
//DrawBoard(board);
}
public static void Main()
{
Introduction();
while(true)
{
bool isrow = false;
bool iscol = false;
int row = 0;
int col = 0;
while (!isrow)
{
Console.WriteLine("Choose a row (1-3): ");
try
{
row = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (row == 1 || row == 2 || row == 3)
{
isrow = true;
}
else
{
Console.WriteLine("\nInvalid row!");
}
}
while (!iscol)
{
Console.WriteLine("Choose a column (1-3): ");
try
{
col = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (col == 1 || col == 2 || col == 3)
{
iscol = true;
}
else
{
Console.WriteLine("\nInvalid column!");
}
}
int[] input = { row, col };
int player = 2;
if (player == 2)
{
player = 1;
XorO(player, input);
}
else
{
player = 2;
XorO(player, input);
}
DrawBoard(board);
turns++;
CheckForDiagonal();
CheckForVertical();
CheckForHorizontal();
if (turns == 10 && (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature && board[3] == playerSignature &&
board[4] == playerSignature && board[5] == playerSignature && board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature))
{
Draw();
}
}
}
private static void CheckForVertical()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[3] == playerSignature && board[6] == playerSignature ||
board[1] == playerSignature && board[4] == playerSignature && board[7] == playerSignature ||
board[2] == playerSignature && board[5] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForHorizontal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature ||
board[3] == playerSignature && board[4] == playerSignature && board[5] == playerSignature ||
board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForDiagonal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[6] == playerSignature && board[4] == playerSignature && board[2] == playerSignature ||
board[0] == playerSignature && board[4] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void XorO(int player, int[] input)
{
if (player == 1)
{
playerSignature = 'X';
}
else if (player == 2)
{
playerSignature = 'O';
}
if (input[0] == 1 && input[1] == 1)
{
board[0] = playerSignature;
}
else if (input[0] == 1 && input[1] == 2)
{
board[1] = playerSignature;
}
else if (input[0] == 1 && input[1] == 3)
{
board[2] = playerSignature;
}
else if (input[0] == 2 && input[1] == 1)
{
board[3] = playerSignature;
}
else if (input[0] == 2 && input[1] == 2)
{
board[4] = playerSignature;
}
else if (input[0] == 2 && input[1] == 3)
{
board[5] = playerSignature;
}
else if (input[0] == 3 && input[1] == 1)
{
board[6] = playerSignature;
}
else if (input[0] == 3 && input[1] == 2)
{
board[7] = playerSignature;
}
else if (input[0] == 3 && input[1] == 3)
{
board[8] = playerSignature;
}
}
}
}
I have tried adding something like this: if(input[0] == 1 && input[1] == 1 && (board[0] != 'X' && board[0] != 'O') in the XorO method. But that didn't solve my issue.
Does somebody maybe have some suggestions as to how I can fix that?
You are doing way too much work in some of those methods...
For instance, here's a shorter XorO() method that also makes sure the spot is BLANK before assigning it to a player:
private static void XorO(int player, int[] input)
{
playerSignature = (player == 1) ? 'X' : 'O';
int index = ((input[0] - 1) * 3) + (input[1] - 1);
if (board[index] == ' ') {
board[index] = playerSignature;
}
else {
// ... output an error message? ...
Console.WriteLine("That spot is already taken!");
}
}
Could you maybe explain why you set index the way you did?
Sure! Here is the layout of the board, 3 rows with 3 cols, and the corresponding Index value of each position:
1 2 3
1 0 1 2
2 3 4 5
3 6 7 8
Note that because there are 3 columns, the value of the Index as we move down from one row to the next in the same column goes up by 3. Also note that the starting values in column 1 for each row are 0, 3, and 6, which are all multiples of 3. So to convert your row value from 1, 2, and 3 into 0, 3, and 6, we first subtract 1 from the row value and then multiply it by 3.
Next, each column simply increments by one as you move to the right. Thus we subtract one from the column value and add that to the computed beginning row value. This maps the (row, col) to the indices 0 through 8, seen here as a single dimension array:
1,1 | 1,2 | 1,3 | 2,1 | 2,2 | 2,3 | 3,1 | 3,2 | 3,3
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
But how was am I supposed to think of something like that? I would
never have thought of that.
It's a fairly common setup to represent a 2D structure in a single dimensional array, known as a compact layout. The math involved to convert a row/column to the equivalent index value or vice-versa is just something that all programmers learn at some point.
Lot of refactoring here, look closely:
class Program
{
static int turns;
static char[] board;
static bool playerOne;
public static void Main(string[] args)
{
Introduction();
bool playAgain = true;
while (playAgain)
{
ResetBoard();
bool gameOver = false;
while (!gameOver)
{
DrawBoard(board);
int row = getNumber(true);
int col = getNumber(false);
if (XorO(row, col)) {
turns++; // valid move was made
String msg = "";
String playerNumber = playerOne ? "1" : "2";
if (CheckForDiagonal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a diagonal win!";
}
else if (CheckForVertical())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a vertical win!";
}
else if (CheckForHorizontal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a horizontal win!";
}
else if (turns == 9)
{
gameOver = true;
msg = "It's a draw!";
}
else
{
playerOne = !playerOne;
}
if (gameOver)
{
DrawBoard(board); // show last move
Console.WriteLine(msg);
}
}
}
Console.WriteLine("Play again (y/n)?");
string response = Console.ReadLine().ToLower();
playAgain = (response == "y");
}
}
private static void ResetBoard()
{
turns = 0;
playerOne = true;
board = new char[] {
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
}
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game.\nEnter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine().ToLower();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
}
}
private static void DrawBoard(char[] board)
{
Console.WriteLine(" ___ ___ ___ ");
for(int r=1; r<=3;r++)
{
Console.Write("|");
for(int c=1; c<=3; c++)
{
Console.Write(" {0} |", board[(r - 1) * 3 + (c - 1)]);
}
Console.WriteLine();
Console.WriteLine("|___|___|___|");
}
}
private static int getNumber(bool row)
{
int value = -1;
string description = row ? "row" : "column";
bool isValid = false;
while (!isValid)
{
Console.Write("Player '" + (playerOne ? "X" : "O") + "', choose a " + description + " (1-3): ");
if (int.TryParse(Console.ReadLine(), out value))
{
if (value >= 1 && value <= 3)
{
isValid = true;
}
else
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
}
else
{
Console.WriteLine("\nInvalid " + description + "!");
}
}
return value;
}
private static bool XorO(int row, int col)
{
int index = ((row - 1) * 3) + (col - 1);
if (board[index] == ' ')
{
board[index] = playerOne ? 'X' : 'O';
return true;
}
else
{
Console.WriteLine("That spot is already taken!");
return false;
}
}
private static bool CheckForDiagonal()
{
return ((board[6] != ' ' && board[4] == board[6] && board[2] == board[6]) ||
(board[0] != ' ' && board[4] == board[0] && board[8] == board[0]));
}
private static bool CheckForVertical()
{
for(int c=0; c<=2; c++)
{
if (board[c] != ' ' && board[c+3] == board[c] && board[c+6] == board[c])
{
return true;
}
}
return false;
}
private static bool CheckForHorizontal()
{
for (int r=0; r<=6; r=r+3)
{
if (board[r] != ' ' && board[r + 1] == board[r] && board[r + 2] == board[r])
{
return true;
}
}
return false;
}
}
I tried to have a console app that takes 5 numbers and fills an array with it but The issue with this code is that, it only accepts 4 numbers and fills the last index with null, how could I fix that?
string[] numbers = new string[4];
Console.WriteLine("Hi, Enter 5 numbers!");
ConsoleKeyInfo key;
for (int i = 0; i < numbers.Length; i++)
{
string _val = "";
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
numbers[i] = _val;
}
Console.WriteLine();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(i + " : " + numbers[i]);
}
Console.WriteLine(numbers.Length);
Console.ReadKey();
}
In the code string[] numbers = new string[4]; means numbers array size is 4 and array starts with 0 index. Hence last index is not null. Change the string[4] to string[5]. Hope this will solve your problem.
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 5 years ago.
I want each Sword to have random name and price but they all get the same random name and price if i run the program without debug from Visual Studio.
I tried running the code line by line in Visual Studio and it actually worked fine.
Can someone explain me why this is happening, I am very confused...
using System;
namespace HomeA
{
class Swords
{
public string name;
public int price;
public bool availableToBuy;
}
class MainClass
{
public static void Main ()
{
bool exitShop = false;
// Name Input and Gold Reward
string userName = MyReadString ("Hello Stranger! What's your Name?");
int userGold = new Random ().Next (40, 120);;
Console.Clear ();
// Generate Random Array of Swords
Swords[] arrayOfSwords = GenerateRandomSwords();
do{ // Shop Loop
// Welcome Message and Choose Input!
Console.WriteLine (new String('-', 29 + userName.Length) + "\n Welcome " + userName + " to the Sword Shop!" +
"\n You have " + userGold + " Gold!\n" + new String('-', 29 + userName.Length) +
"\n1. Buy a Sword!\n2. Sell a Sword(Coming Soon)!\n3. Display my Swords(Coming Soon)!\n0. Continue your Adventure!\n\n");
int menuInput = MyReadInt ("What would you like to do?", 0, 3);
Console.WriteLine (menuInput);
if(menuInput == 0) // Exit
{
exitShop = true;
Console.Clear();
}else if(menuInput == 1) // Buy
{
Console.Clear();
Console.WriteLine (new String('-', 37) +
"\n You have " + userGold + " Gold available to spend!\n" +
new String('-', 37));
// Display all Available Swords
for(int i = 0; i <= arrayOfSwords.Length -1; i++)
{
if(arrayOfSwords[i].availableToBuy)
{
Console.WriteLine("{0}. Swords of {1} is available for {2} Gold!", (i+1), arrayOfSwords[i].name, arrayOfSwords[i].price);
}
}
// 1 Additional Option to go Back to the Shop
Console.WriteLine("{0}. Go Back!", arrayOfSwords.Length + 1);
// Get Input which Sword to Buy
bool loopAgain = false;
do
{ // Check if it's Available to Buy
int userBuyMenuInput = MyReadInt("\n\nWhich Sword would you like to Buy?", 1, arrayOfSwords.Length + 1);
if(userBuyMenuInput == arrayOfSwords.Length + 1)
{ // Exit to Shop Page
Console.Clear();
break;
}
if(arrayOfSwords[userBuyMenuInput - 1].availableToBuy == false)
{
loopAgain = true;
Console.WriteLine("There is no Sword with number {0}!", userBuyMenuInput);
}else
{
Console.Clear();
if(userGold >= arrayOfSwords[userBuyMenuInput - 1].price)
{ // Buy, deduct the gold and Output a message
arrayOfSwords[userBuyMenuInput - 1].availableToBuy = false;
userGold -= arrayOfSwords[userBuyMenuInput - 1].price;
Console.WriteLine("You Successfully Bought the Sword of {0}!", arrayOfSwords[userBuyMenuInput - 1].name);
loopAgain = false;
}else
{
Console.WriteLine("You Don't have enought Gold to buy the Sword of {0}!", arrayOfSwords[userBuyMenuInput - 1].name);
loopAgain = false;
}
}
}while(loopAgain);
}else if (menuInput == 2) // Sell
{
Console.Clear();
}else // Display
{
Console.Clear();
}
}while(!exitShop);
}
public static string MyReadString(string messageToDisplay)
{
string result;
do // Making sure input is not null
{
Console.WriteLine(messageToDisplay);
result = Console.ReadLine();
}while(result == null);
return result;
}
public static int MyReadInt(string messageToDisplay, int minAllowed, int maxAllowed)
{
int result;
do // Making sure input is within min and max Allowed
{
result = int.Parse(MyReadString(messageToDisplay));
if(result < minAllowed || result > maxAllowed) Console.WriteLine("Invalid Input! You must give a number between {0} and {1}!", minAllowed, maxAllowed);
}while(result < minAllowed || result > maxAllowed);
return result;
}
public static Swords[] GenerateRandomSwords()
{
// Create an Array of Swords of Random Length
Swords[] result = new Swords[new Random().Next (3, 9)];
// Populate each Instance of Swords with random values and make it available to buy
for (int i = 0; i <= result.Length - 1; i++)
{
result [i] = new Swords ();
result [i].name = GenerateRandomStringFromInt();
result [i].price = new Random ().Next (10, 30);
result [i].availableToBuy = true;
}
return result;
}
public static string GenerateRandomStringFromInt()
{
string result = "";
int loopXAmountOfTimes = new Random().Next(3, 8), loopCount = 0, randomInt;
do
{
// Add a char accouring to a random int
randomInt = new Random ().Next (1, 26);
if(randomInt == 1)
{
result += 'A';
}else if(randomInt == 2)
{
result += 'B';
}else if(randomInt == 3)
{
result += 'C';
}else if(randomInt == 4)
{
result += 'D';
}else if(randomInt == 5)
{
result += 'E';
}else if(randomInt == 6)
{
result += 'F';
}else if(randomInt == 7)
{
result += 'G';
}else if(randomInt == 8)
{
result += 'H';
}else if(randomInt == 9)
{
result += 'I';
}else if(randomInt == 10)
{
result += 'J';
}else if(randomInt == 11)
{
result += 'K';
}else if(randomInt == 12)
{
result += 'L';
}else if(randomInt == 13)
{
result += 'M';
}else if(randomInt == 14)
{
result += 'N';
}else if(randomInt == 15)
{
result += 'O';
}else if(randomInt == 16)
{
result += 'P';
}else if(randomInt == 17)
{
result += 'Q';
}else if(randomInt == 18)
{
result += 'R';
}else if(randomInt == 19)
{
result += 'S';
}else if(randomInt == 20)
{
result += 'T';
}else if(randomInt == 21)
{
result += 'U';
}else if(randomInt == 22)
{
result += 'V';
}else if(randomInt == 23)
{
result += 'W';
}else if(randomInt == 24)
{
result += 'X';
}else if(randomInt == 25)
{
result += 'Y';
}else
{
result += 'Z';
}
loopCount++;
}while(loopCount <= loopXAmountOfTimes);
return result;
}
}
}
Looking at the code and the comment to you, save the Random object you create once your application starts.
Then when you need a random value, call .Next() on it to return your new random number.
Console.Write("Hoeveel worpen wil je simuleren: ");
int worpen = int.Parse(Console.ReadLine());
Random r = new Random(worpen);
int willekeur = r.Next(1, worpen);
double willekeur1 = willekeur;
Math.Round(willekeur1);
for (int i = 1; i <= 12; i++)
{
Console.WriteLine("ik gooide "+willekeur+" ("+Math.Round(willekeur1,2,)+")");
willekeur = r.Next(1, worpen);
}
Console.ReadLine();
I want that ' willekeur1 ' a number which contains a decimal comma is. so example: 12456--> 12,456
You can do: (you need latest c# to use string interpolation)
$"{12456:n0}"; // 12,456
$"{12456:n2}"; // 12,456.00
In your case
Console.WriteLine($"ik gooide {willekeur} ({Math.Round(willekeur1,2,)})");
or
$"{Math.Round(willekeur1,2):n0}";
$"{Math.Round(willekeur1,2):n2}";
this might be useful for you:
public float ReadFloat()
{
float ReadValue = 0;
string KeySequence = "";
string TempKey = "";
bool CommaUsed = false;
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if ((key.Key >= ConsoleKey.D0 && key.Key <= ConsoleKey.D9) || (key.Key >= ConsoleKey.NumPad0 && key.Key <= ConsoleKey.NumPad9))
{
TempKey = Convert.ToString(key.Key);
TempKey = TempKey.Remove(0, 1);
KeySequence += TempKey;
Console.Write(TempKey);
};
if (key.Key == ConsoleKey.OemComma || key.Key == ConsoleKey.Decimal)
{
if (!CommaUsed)
{
KeySequence += ".";
Console.Write(".");
CommaUsed = true;
};
};
if ((key.Key == ConsoleKey.Backspace) && KeySequence != "")
{
string LastChar = KeySequence.Substring(KeySequence.Length - 1);
//MessageBox.Show("Last char: "+LastChar);
//Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
char SepDeci = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (Convert.ToChar(LastChar) == SepDeci)
{
CommaUsed = false;
};
KeySequence = KeySequence.Remove(KeySequence.Length - 1);
Console.Write("\b \b");
};
}
while (key.Key != ConsoleKey.Enter);
if (KeySequence == "")
{
return 0;
};
ReadValue = Convert.ToSingle(KeySequence);
return ReadValue;
}
this method reads value from console but allows only numbers and one decimal separator (comma or dot, depending on your culture settings).
to use is to read value to a variable:
willekeur1 = ReadFloat();
I have strings like:
1) Cookie:ystat_tw_ss376223=9_16940400_234398;
2) Cookie:zynga_toolbar_fb_uid=1018132522
3) GET /2009/visuels/Metaboli_120x600_UK.gif HTTP/1.1
4) GET /2010/07/15/ipad-3hk-smv-price-hk/ HTTP/1.1
1 ad 2 have common substtring{cookie:}
3 and 4 have common substtring{GET /20, HTTP/1.1}
I want to find all common substrings that have the length more than three characters(contain space character) between 2 strings.(like 1 and 2)
i want to code in c#. i have a program but it has some problems.
Could anyone help me?
public static string[] MyMCS2(string a, string b)
{
string[] st = new string[100];
// List<string> st = new List<string>();
List<char> f = new List<char>();
int ctr = 0;
char[] str1 = a.ToCharArray();
char[] str2 = b.ToCharArray();
int m = 0;
int n = 0;
while (m < str1.Length)
{
for (n = 0; n < str2.Length; n++)
{
if (m < str1.Length)
{
if (str1[m] == str2[n])
{
if ((m > 1) && (n > 1) &&(str1[m - 1] == str2[n - 1]) && (str1[m - 2] == str2[n - 2]))
{
//f[m]= str1[m];
f.Add(str1[m]);
char[] ff = f.ToArray();
string aaa = new string(ff);
if (aaa.Length >= 3)
{
st[ctr] = aaa + "()";
//st.Add(aaa);
ctr++;
}
kk = m;
m++;
}
else if ((n == 0) ||(n == 1))
{
f.Add(str1[m]);
kk = m;
m++;
}
else
f.Clear();
}
//else if ((str1[m] == str2[n]) && (m == str1.Length - 1) && (n == str2.Length - 1))
//{
// f.Add(str1[m]);
// char[] ff = f.ToArray();
// string aaa = new string(ff);
// if (aaa.Length >= 3)
// {
// st[ctr] = aaa;
// ctr++;
// }
// // m++;
//}
else if ((str1[m] != str2[n]) && (n == (str2.Length - 1)))
{
m++;
}
else if ((m > 1) && (n > 1) && (str1[m] != str2[n]) && (str1[m - 1] == str2[n - 1]) && (str1[m - 2] == str2[n - 2]) && (str1[m - 3] == str2[n - 3]))
{
//
char[] ff = f.ToArray();
string aaa = new string(ff);
if (aaa.Length >= 3)
{
st[ctr] = aaa + "()" ;
//st.Add(aaa);
ctr++;
f.Clear();
}
//f.Clear();
//for (int h = 0; h < ff.Length; h++)
//{
// f[h] = '\0';
//}
}
else if (str1[m] != str2[n])
continue;
}
}
}
//int gb = st.Length;
return st;
}
This is an exact matching problem not a substring. You can solve it with aho-corasick algorithm. Use the first string and compute a finite state machine. Then process the search string. You can extend the aho-corasick algorithm to use a wildcard and search also for substrings. You can try this animated example: http://blog.ivank.net/aho-corasick-algorithm-in-as3.html