How can i parse variable length strings - c#

I'm trying to take multiple lines from a TextBox to use different parts of the text to draw shapes. So far I have this:
public partial class Form1 : Form
{
const int BitmapX = 640;
const int BitmapY = 480;
//bitmap which will be displayed on picturebox
Bitmap OutputBitmap = new Bitmap(BitmapX, BitmapY);
Bitmap CursorBM = new Bitmap(BitmapX, BitmapY);
Graphics bmG;
Canvas MyCanvas;
public bool Checked = false
public Form1()
{
InitializeComponent();
bmG = Graphics.FromImage(OutputBitmap);
MyCanvas = new Canvas(Graphics.FromImage(OutputBitmap));
}
private void button1_Click(object sender, EventArgs e)
{
string[] Lines = ProgramWindow.Text.Split('\n');
int NumberOfCommands = Lines.Length;
{
for (int i = 0; i <= NumberOfCommands - 1; i++)
{
int VariableValue = 0;
string[] Input = Lines[i].ToLower().Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
string Command = Input[0];
string input1 = Input.Length >= 2 ? Input[0] : " ";
string input2 = Input.Length >= 3 ? Input[1] : " ";
string input3 = Input.Length >= 4 ? Input[2] : " ";
string input4 = Input.Length >= 5 ? Input[3] : " ";
Console.WriteLine(Command, input1, input2, input3, input4);
Commands(Command, VariableValue, input1, input2, input3, input4);
Refresh();
}
}
void Commands(string Command, int VariableValue, string input1, string input2, string input3, string input4)
{
if (input1.Equals("="))
{
int Value = int.Parse(input2);
VariableValue = Value;
if (input3.Equals("+"))
{
int AddValue = int.Parse(input4);
VariableValue = VariableValue + AddValue;
}
else if (input3.Equals("*"))
{
int TimesValue = int.Parse(input4);
VariableValue = VariableValue * TimesValue;
}
}
}
The commands I'm trying to type can be multiple formats which is where I'm having a problem the commands can be in the following formats :
string = int
string = int + int
string int
I'm trying to parse them all as strings so I can parse certain ones as
int's later as needed, but currently I can't get different lengths of text without an 'out of bounds'.

Related

JS decryption method translate to C#

I need some help with JS code translation to C#.
JS Code:
function Decription(string) {
var newString = '',
char, codeStr, firstCharCode, lastCharCode;
var ft = escape(string);
string = decodeURIComponent(ft);
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char > 132) {
codeStr = char.toString(10);
firstCharCode = parseInt(codeStr.substring(0, codeStr.length - 2), 10);
lastCharCode = parseInt(codeStr.substring(codeStr.length - 2, codeStr.length), 10) + 31;
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
} else {
newString += string.charAt(i);
}
}
return newString;
}
And I tied to translate on C#:
private string Decription(string encriptedText)
{
string ft = Regex.Escape(encriptedText);
string text = HttpUtility.UrlDecode(ft);
string newString = "";
for (int i = 0; i < text.Length; i++)
{
var ch = (int)text[i];
if(ch > 132)
{
var codeStr = Convert.ToString(ch, 10);
var firstCharCode = Convert.ToInt32(codeStr.Substring(0, codeStr.Length - 2), 10);
var lastCharCode = Convert.ToInt32(codeStr.Substring(codeStr.Length - 2, codeStr.Length), 10) + 31;
}
}
}
But how I can translate this row:
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
Maybe do you know equivalent method to String.fromCharCode() on C# ?
Here you go:
public static void Main()
{
// from 97 to a
int i = 97;
Console.WriteLine(StringFromCharCode(97));
}
public static string StringFromCharCode(int code) => ((char)code).ToString();
Demo
Note that you may want to use a StringBuilder instead of concatening string in your case.
Related to Int to Char in C# (Read it. It includes a nice comment about cast vs Convert.ToChar)
You can simply use Convert.ToChar method, Convert.ToChar(97) will return a.

ArgumentOutOfRangeException: startIndex cannot be longer than the length of string

When I run the compiler it throws an exception:
ArgumentOutOfRangeException: startIndex cannot be longer than the
length of string.
I do not understand why, the string which I write into the compiler consists of 10 numbers, and i want the substring to pick the 9th number, but obviously I'm doing something wrong.
Example of string: 9303140456
Code:
public string kollaKön()
{
string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
Complete code, maybe makes my mistake obvious:
namespace WindowsFormsApplication3
{
public class Person
{
Form1 form = new Form1();
string förnamn;
string efternamn;
string personnummer;
string Kön;
public Person(string förNamn, string efterNamn, string personNummer)
{
string förnamn = förNamn;
string efternamn = efterNamn;
string personnummer = personNummer;
}
static bool luhn(string personNummer)
{
int sum = 0;
for (int i = 0; i < personNummer.Length; i++)
{
int temp = (personNummer[i] - '0') << (1 - (i & 1));
if (temp > 9) temp -= 9;
sum += temp;
}
return (sum % 10) == 0;
}
public string kollaKön()
{
string debuggerIsMyFriend = form.textBox3.Text;
string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string förnamn = textBox1.Text;
string efternamn = textBox2.Text;
string personnummer = textBox3.Text;
string persnr = "";
if (personnummer.Length != 10)
{
persnr = " Personnummer är i fel format. ";
}
if (personnummer.Length == 10)
{
persnr = " Personnummers är i korrekt format.";
}
Person p1 = new Person(förnamn, efternamn, personnummer);
p1.kollaKön();
textBox4.Text = förnamn + " " + efternamn + " " + personnummer + " " + " " + persnr;
}
}
}
This line in your Person class
Form1 form = new Form1();
declares and initialize a new Instance of Form1. This instance is not the one that you have shown on your monitor. When you type your strings you type them on the instance that is shown on monitor not into the textboxes of this hidden instance.
Of course this means that when you write
string siffraAsString = form.textBox3.Text.Substring(8, 1);
you are taking the text of the hidden textbox that is empty and the following Substring code fails with the Index Out of Range Exception
You need to change you Person class and add properties that receive the content of the textboxes required for your calculations.
For example
public class Person
{
// Sorry but I have no idea of what Siffra means...
// change the name as you wish
public string Siffra {get;set;}
...... other properties
public string kollaKön()
{
// A defensive attitude is always a good practice.
if(string.IsNullOrEmpty(this.Siffra) ||
this.Siffra.Length < 10)
return "Invalid Siffra";
string siffraAsString = this.Siffra.Substring(8, 1);
int siffraAsNum = int.Parse(siffraAsString);
int result = (siffraAsNum % 2);
return (result == 1 ? "Är en Man" : " Är en Kvinna");
}
}
and in your button click on the form you run
.....
Person p1 = new Person(förnamn, efternamn, personnummer);
p1.Siffra = this.textBox3.Text;
string result = p1.kollaKön();
this.textBox5.Text = result;
Before all your code, add this line
string debuggerIsMyFriend = form.textBox3.Text;
Set a breakpoint on that line, run the code and hover the mouse over the variable to see what it actually contains, I bet it's not the 10 characters string you are expecting
You should handle this more gracefully. This will handle your edge cases properly.
The string you're getting in that TextBox is most certainly not 9 characters long or more, and unless you have 100% certainty that your input is 9 characters, you should handle it gracefully.
Rule of thumb: Don't try to access the index of an array without checking its length first.
...Second rule of thumb: Also make sure you're accessing the correct UI control if you think something's fishy.
public string kollaKön()
{
//string siffraAsString = form.textBox3.Text.Substring(8, 1);
int siffraAsNum = GetNinthNumber(form.textBox3.Text);
int result = (siffraAsNum % 2);
if (result == 1)
{
return form.textBox5.Text = ("Är en Man");
}
else
{
return form.textBox5.Text = (" Är en Kvinna");
}
}
public static int GetNinthNumber(string str)
{
string numberField = str.Trim();
if (numberField.Length < 9)
{
// Handle less than 9 cases
return 0;
}
else
{
int number;
bool isNumber = Int32.TryParse(str[8].ToString(), out number);
if (!isNumber)
{
throw new Exception("Value is not a number");
}
return number;
}
}
I'm very sure that your line string siffraAsString = form.textBox3.Text.Substring(8, 1); doesn't have 10 numbers.
Checks the value of form.textBox3.Text as say Jacopo.

How to get the first 4 letters to be uppercase letter in the next Textbox?

New to programing and its a user/password generator. I want to have the first 4 letters in every name from the left textbox and the result should be 4 uppercase letters (i) same 4 uppercase letter / password generated
ex:
Adair Ewing
Zorro Irving
(Pusching generatbutton)
(Result)
ADAI0ASAI / dkfnwkef
ZOOR1ZOOR / woeknfwe
My code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonGenerat_Click(object sender, EventArgs e)
{
char[] radbytning = new char[]{'\r', '\n'};
string[] name = textBoxLeft.Text.Split(radbytning, StringSplitOptions.RemoveEmptyEntries);
string result = "";
for (int i = 0; i <name.Length; i++)
{
result += string.Format("{0}{1}{0} / {2}\r\n", name[i].Substring(0, 4), i, GeneratPassword());
}
textBoxRight.Text = result;
}
private static string GeneratPassword()
{
string result = "";
String tecken = "abcdefghijklmnopqrstuvxyzåäö1234567890ABCDEFGHIJKLMNOPQRSTUVXYZÅÄÖ";
Random random = new Random();
for(int i = 0; i< 8; i++)
{
result += tecken[random.Next(tecken.Length)].ToString();
System.Threading.Thread.Sleep(10);
}
return result;
}
public string FirstLetterToUpper(string)
{
if (str == null)
return null;
if (str.Length > 1)
return char.ToUpper(str[0]) + str.Substring(1);
return str;
}
}
}
This line of code throws an error because there is no variable attached to the "string" you will be passing public string FirstLetterToUpper(string)
However, I don't think you need this function at all and you don't even call it in your code.
I think you just need to change the following line of code to get what you want and delete the Function I mention above:
result += string.Format("{0}{1}{0} / {2}\r\n", name[i].Substring(0, 4), i, GeneratPassword());
Change to:
result += string.Format("{0}{1}{0} / {2}\r\n", name[i].Substring(0, 4).ToUpper(), i, GeneratPassword());
That then gives an output
ADAI0ADAI / CMldQQY7
ZORR0ZORR / e3sbdxJQ
I think this is what you are getting at, and that you have multiple typos in this part of your question!

C# formatting output of methods from a class and no data is displayed now

So I wanted to format this text so it was being padded and was all nice and square not dependant on the length of different address sizes or names. However now that its in this format...nothing shows up in regard to the actuall variables and values.
Before I did
Console.WriteLine(emp[i].GetEmpName());
and it worked fine, it displayed the string stored in that method. now I am unsure where the disconnect is but it now is displaying a blank value such as
Employee Name:
EmployeeAddress:
so forth.
for (int i = 0; i < count; i++)
{
string eNum = "Employee Number: ";
string eName = "Emplyee Name: ";
string eAddress = "Employee Address: ";
Console.WriteLine("------------------------------------------------------------------------");
Console.Write("|");
Console.Write(eNum.PadRight(30), emp[i].GetEmpNum());
Console.Write("|\n");
Console.Write("|");
Console.Write(eName.PadRight(30), emp[i].GetEmpName());
Console.Write("|\n");
Console.Write("|");
Console.Write(eAddress.PadRight(30), emp[i].GetEmpAddress());
Console.Write("|\n");
//Console.Write();
//Console.Write();
Console.Write("|");
Console.Write("Net Pay: {0:f2}", emp[i].CalcSalary());
Console.WriteLine("\n------------------------------------------------------ ------------------\n\n");
}
The rest of the code is here if you want to see it. Again it works as long as you dont format the output.
Where did I go so horribly wrong?!?!
using System;
using System.IO;
namespace Proj10
{
class Program
{
const int ARRAY_TWO = 2;
static void Main()
{
int count = 0;
Employee[] emp = new Employee[10];
string environment = System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Personal) + "\\";
Console.WriteLine("Enter a file name in My Documents: ");
string input = Console.ReadLine();
string path = environment + input;
StreamReader myFile = new StreamReader(path);
do
{
if (myFile.EndOfStream)
{
break;
}
int num = int.Parse(myFile.ReadLine());
string name = myFile.ReadLine();
string address = myFile.ReadLine();
string hourNworked = myFile.ReadLine();
double[] values = new double[ARRAY_TWO];
sort(hourNworked, ref values);
emp[count] = new Employee();
emp[count].SetEmpNum(num);
emp[count].SetEmpName(name);
emp[count].SetEmpAddress(address);
emp[count].SetEmpHrlyPay(values[0]);
emp[count].SetEmpHrsWrked(values[1]);
//while count < 10 && !myfile.EOF();
//print loop using count
//emp[0].GetEmpNum();
//emp[0].CalcSalary();
/*Integer[] number = new Integer[5];
for (int i = 0; i < 5; i++)
number[i] = new Integer(i);
for (int i = 0; i < 5; i++)
Console.WriteLine(number[i].GetValue());
*/
count++;
} while (count < 10);
Console.WriteLine("\n\nAuthor: Daniel Demers");
Console.WriteLine("CS 1400 X01\n");
for (int i = 0; i < count; i++)
{
string eNum = "Employee Number: ";
string eName = "Emplyee Name: ";
string eAddress = "Employee Address: ";
Console.WriteLine("------------------------------------------------------------------------");
Console.Write("|");
Console.Write(eNum.PadRight(30), emp[i].GetEmpNum());
Console.Write("|\n");
Console.Write("|");
Console.Write(eName.PadRight(30), emp[i].GetEmpName());
Console.Write("|\n");
Console.Write("|");
Console.Write(eAddress.PadRight(30), emp[i].GetEmpAddress());
Console.Write("|\n");
//Console.Write();
//Console.Write();
Console.Write("|");
Console.Write("Net Pay: {0:f2}", emp[i].CalcSalary());
Console.WriteLine("\n------------------------------------------------------------------------\n\n");
}
Console.ReadLine();
}
public static void sort(string hourNworked, ref double[] values)
{
char[] rules = { ' ' };
string[] splitArray = hourNworked.Split(rules);
values[0] = double.Parse(splitArray[0]);
values[1] = double.Parse(splitArray[1]);
}
public class Employee
{
private int empNum;
private string name;
private string address;
private double hrlyPay;
private double hrsWrkd;
private double GROSS;
private double overTime;
private double overTimePay;
private double overTimeHours;
private double NET;
private double regTime;
private double fTaxAmount;
private double sTaxAmount;
private const double FED_TAX = .20;
private const double STATE_TAX = .075;
private const double OT_MULTIPLYER = 1.5;
private const int FORTY_HOURS = 40;
public Employee()
{
empNum = 0;
}
public void SetEmpNum(int n)
{
empNum = n;
}
public int GetEmpNum()
{
return empNum;
}
public void SetEmpName(string n)
{
name = n;
}
public string GetEmpName()
{
return name;
}
public void SetEmpAddress(string a)
{
address = a;
}
public string GetEmpAddress()
{
return address;
}
public void SetEmpHrlyPay(double h)
{
hrlyPay = h;
}
public double GetEmpHrlyPay()
{
return hrlyPay;
}
public void SetEmpHrsWrked(double w)
{
hrsWrkd = w;
}
public double GetEmpHrsWrkd()
{
return hrsWrkd;
}
public double CalcSalary()
{
if (hrsWrkd > 40)
{
overTimeHours = hrsWrkd - FORTY_HOURS;
overTimePay = hrlyPay * OT_MULTIPLYER;
overTime = overTimePay * overTimeHours;
regTime = (hrsWrkd - overTimeHours) * hrlyPay;
GROSS = overTime + regTime;
fTaxAmount = (regTime + overTime) * FED_TAX;
sTaxAmount = (regTime + overTime) * STATE_TAX;
NET = GROSS - (fTaxAmount + sTaxAmount);
return NET;
}
else
{
regTime = hrlyPay * hrsWrkd;
fTaxAmount = regTime * FED_TAX;
sTaxAmount = regTime * STATE_TAX;
NET = regTime - (fTaxAmount + sTaxAmount);
return NET;
}
}
}
}
}
The Console.Write overload you are using takes a format string and an object. Since your first argument does not contain any placeholders, the second argument is not used.
Try this instead:
Console.WriteLine("|{0,-30}{1,-20}|", eNum, emp[i].GetEmpNum());
See it working online: ideone

Find text in string with C#

How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:
This is an example string and my data is here
And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.
Use this method:
public static string getBetween(string strSource, string strStart, string strEnd)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
How to use it:
string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
This is the simplest way:
if(str.Contains("hello"))
You could use Regex:
var regex = new Regex(".*my (.*) is.*");
if (regex.IsMatch("This is an example string and my data is here"))
{
var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value;
Console.WriteLine("This is my captured text: {0}", myCapturedText);
}
string string1 = "This is an example string and my data is here";
string toFind1 = "my";
string toFind2 = "is";
int start = string1.IndexOf(toFind1) + toFind1.Length;
int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
string string2 = string1.Substring(start, end - start);
Here's my function using Oscar Jara's function as a model.
public static string getBetween(string strSource, string strStart, string strEnd) {
const int kNotFound = -1;
var startIdx = strSource.IndexOf(strStart);
if (startIdx != kNotFound) {
startIdx += strStart.Length;
var endIdx = strSource.IndexOf(strEnd, startIdx);
if (endIdx > startIdx) {
return strSource.Substring(startIdx, endIdx - startIdx);
}
}
return String.Empty;
}
This version does at most two searches of the text. It avoids an exception thrown by Oscar's version when searching for an end string that only occurs before the start string, i.e., getBetween(text, "my", "and");.
Usage is the same:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
You can do it compactly like this:
string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
Except for #Prashant's answer, the above answers have been answered incorrectly. Where is the "replace" feature of the answer? The OP asked, "After that, I'd like to create a new string between that and something else".
Based on #Oscar's excellent response, I have expanded his function to be a "Search And Replace" function in one.
I think #Prashant's answer should have been the accepted answer by the OP, as it does a replace.
Anyway, I've called my variant - ReplaceBetween().
public static string ReplaceBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
string strToReplace = strSource.Substring(Start, End - Start);
string newString = strSource.Concat(Start,strReplace,End - Start);
return newString;
}
else
{
return string.Empty;
}
}
static void Main(string[] args)
{
int f = 0;
Console.WriteLine("enter the string");
string s = Console.ReadLine();
Console.WriteLine("enter the word to be searched");
string a = Console.ReadLine();
int l = s.Length;
int c = a.Length;
for (int i = 0; i < l; i++)
{
if (s[i] == a[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (s[K] == a[j])
{
f++;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
string WordInBetween(string sentence, string wordOne, string wordTwo)
{
int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;
int end = sentence.IndexOf(wordTwo) - start - 1;
return sentence.Substring(start, end);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace oops3
{
public class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Enter the string");
string x = Console.ReadLine();
Console.WriteLine("enter the string to be searched");
string SearchText = Console.ReadLine();
string[] myarr = new string[30];
myarr = x.Split(' ');
int i = 0;
foreach(string s in myarr)
{
i = i + 1;
if (s==SearchText)
{
Console.WriteLine("The string found at position:" + i);
}
}
Console.ReadLine();
}
}
}
This is the correct way to replace a portion of text inside a string (based upon the getBetween method by Oscar Jara):
public static string ReplaceTextBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End, strSourceEnd;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
strSourceEnd = strSource.Length - 1;
string strToReplace = strSource.Substring(Start, End - Start);
string newString = string.Concat(strSource.Substring(0, Start), strReplace, strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start));
return newString;
}
else
{
return string.Empty;
}
}
The string.Concat concatenates 3 strings:
The string source portion before the string to replace found - strSource.Substring(0, Start)
The replacing string - strReplace
The string source portion after the string to replace found - strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start)
Simply add this code:
if (string.Contains("search_text")) {
MessageBox.Show("Message.");
}
If you know that you always want the string between "my" and "is", then you can always perform the following:
string message = "This is an example string and my data is here";
//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;
//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);
//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();
First find the index of text and then substring
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("TEXT To find");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have different approach on ReplaceTextBetween() function.
public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;
var endIndex = strSource.IndexOf(strEnd, startIndex);
var strSourceLength = strSource.Length;
var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);
var concatStart = startIndex + strToReplace.Length;
var beforeReplaceStr = strSource.Substring(0, startIndex);
var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);
return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
}
return strSource;
}
Correct answer here without using any pre-defined method.
static void WordContainsInString()
{
int f = 0;
Console.WriteLine("Input the string");
string str = Console.ReadLine();
Console.WriteLine("Input the word to search");
string word = Console.ReadLine();
int l = str.Length;
int c = word.Length;
for (int i = 0; i < l; i++)
{
if (str[i] == word[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (str[K] == word[j])
{
f++;
}
else
{
f = 0;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
for .net 6 can use next code
public static string? Crop(string? text, string? start, string? end = default)
{
if (text == null) return null;
string? result;
var startIndex = string.IsNullOrEmpty(start) ? 0 : text.IndexOf(start);
if (startIndex < 0) return null;
startIndex += start?.Length ?? 0;
if (string.IsNullOrEmpty(end))
{
result = text.Substring(startIndex);
}
else
{
var endIndex = text.IndexOf(end, startIndex);
if (endIndex < 0) return null;
result = text.Substring(startIndex, endIndex - startIndex);
}
return result;
}

Categories

Resources