I have like a three word expression: "Shut The Door" and I want to find it in a sentence. Since They are kind of seperated by space what would be the best solution for it.
If you have the string:
string sample = "If you know what's good for you, you'll shut the door!";
And you want to find where it is in a sentence, you can use the IndexOf method.
int index = sample.IndexOf("shut the door");
// index will be 42
A non -1 answer means the string has been located. -1 means it does not exist in the string. Please note that the search string ("shut the door") is case sensitive.
Use build in Regex.Match Method for matching strings.
string text = "One car red car blue car";
string pat = #"(\w+)\s+(car)";
// Compile the regular expression.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
int matchCount = 0;
while (m.Success)
{
Console.WriteLine("Match"+ (++matchCount));
for (int i = 1; i <= 2; i++)
{
Group g = m.Groups[i];
Console.WriteLine("Group"+i+"='" + g + "'");
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
}
}
m = m.NextMatch();
}
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.match(v=vs.71).aspx
http://support.microsoft.com/kb/308252
if (string1.indexOf(string2) >= 0)
...
The spaces are nothing special, they are just characters, so you can find a string like this like yuo would find any other string in your sentence, for example using "indexOf" if you need the position, or just "Contains" if you need to know if it exists or not.
E.g.
string sentence = "foo bar baz";
string phrase = "bar baz";
Console.WriteLine(sentence.Contains(phrase)); // True
Here is some C# code to find a substrings using a start string and end string point but you can use as a base and modify (i.e. remove need for end string) to just find your string...
2 versions, one to just find the first instance of a substring, other returns a dictionary of all starting positions of the substring and the actual string.
public Dictionary<int, string> GetSubstringDic(string start, string end, string source, bool includeStartEnd, bool caseInsensitive)
{
int startIndex = -1;
int endIndex = -1;
int length = -1;
int sourceLength = source.Length;
Dictionary<int, string> result = new Dictionary<int, string>();
try
{
//if just want to find string, case insensitive
if (caseInsensitive)
{
source = source.ToLower();
start = start.ToLower();
end = end.ToLower();
}
//does start string exist
startIndex = source.IndexOf(start);
if (startIndex != -1)
{
//start to check for each instance of matches for the length of the source string
while (startIndex < sourceLength && startIndex > -1)
{
//does end string exist?
endIndex = source.IndexOf(end, startIndex + 1);
if (endIndex != -1)
{
//if we want to get length of string including the start and end strings
if (includeStartEnd)
{
//make sure to include the end string
length = (endIndex + end.Length) - startIndex;
}
else
{
//change start index to not include the start string
startIndex = startIndex + start.Length;
length = endIndex - startIndex;
}
//add to dictionary
result.Add(startIndex, source.Substring(startIndex, length));
//move start position up
startIndex = source.IndexOf(start, endIndex + 1);
}
else
{
//no end so break out of while;
break;
}
}
}
}
catch (Exception ex)
{
//Notify of Error
result = new Dictionary<int, string>();
StringBuilder g_Error = new StringBuilder();
g_Error.AppendLine("GetSubstringDic: " + ex.Message.ToString());
g_Error.AppendLine(ex.StackTrace.ToString());
}
return result;
}
public string GetSubstring(string start, string end, string source, bool includeStartEnd, bool caseInsensitive)
{
int startIndex = -1;
int endIndex = -1;
int length = -1;
int sourceLength = source.Length;
string result = string.Empty;
try
{
if (caseInsensitive)
{
source = source.ToLower();
start = start.ToLower();
end = end.ToLower();
}
startIndex = source.IndexOf(start);
if (startIndex != -1)
{
endIndex = source.IndexOf(end, startIndex + 1);
if (endIndex != -1)
{
if (includeStartEnd)
{
length = (endIndex + end.Length) - startIndex;
}
else
{
startIndex = startIndex + start.Length;
length = endIndex - startIndex;
}
result = source.Substring(startIndex, length);
}
}
}
catch (Exception ex)
{
//Notify of Error
result = string.Empty;
StringBuilder g_Error = new StringBuilder();
g_Error.AppendLine("GetSubstring: " + ex.Message.ToString());
g_Error.AppendLine(ex.StackTrace.ToString());
}
return result;
}
You may want to make sure the check ignores the case of both phrases.
string theSentence = "I really want you to shut the door.";
string thePhrase = "Shut The Door";
bool phraseIsPresent = theSentence.ToUpper().Contains(thePhrase.ToUpper());
int phraseStartsAt = theSentence.IndexOf(
thePhrase,
StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine("Is the phrase present? " + phraseIsPresent);
Console.WriteLine("The phrase starts at character: " + phraseStartsAt);
This outputs:
Is the phrase present? True
The phrase starts at character: 21
Related
how can I retrieve both string between STRING & END in this sentence
"This is STRING a222 END, and this is STRING b2838 END."
strings that I want to get:
a222
b2838
Following is my code, and i only manage to get first string which is a222
string myString = "This is STRING a222 END, and this is STRING b2838 END.";
int first = myString.IndexOf("STRING") + "STRING".Length;
int second= myString.LastIndexOf("END");
string result = St.Substring(first, second - first);
.
Here is the solution using Regular Expressions. Working Code here
var reg = new Regex("(?<=STRING ).*?(?= END)");
var matched = reg.Matches("This is STRING a222 END, and this is STRING b2838 END.");
foreach(var m in matched)
{
Console.WriteLine(m.ToString());
}
You can pass a value for startIndex to string.IndexOf(), you can use this while looping:
IEnumerable<string> Find(string input, string startDelimiter, string endDelimiter)
{
int first = 0, second;
do
{
// Find start delimiter
first = input.IndexOf(startDelimiter, startIndex: first) + startDelimiter.Length;
if (first == -1)
yield break;
// Find end delimiter
second = input.IndexOf(endDelimiter, startIndex: first);
if (second == -1)
yield break;
yield return input.Substring(first, second - first).Trim();
first = second + endDelimiter.Length + 1;
}
while (first < input.Length);
}
You can iterate over indexes,
string myString = "This is STRING a222 END, and this is STRING b2838 END.";
//Jump to starting index of each `STRING`
for(int i = myString.IndexOf("STRING");i > 0; i = myString.IndexOf("STRING", i+1))
{
//Get Index of each END
var endIndex = myString.Substring(i + "STARTING".Length).IndexOf("END");
//PRINT substring between STRING and END of each occurance
Console.WriteLine(myString.Substring(i + "STARTING".Length-1, endIndex));
}
.NET FIDDLE
In your case, STRING..END occurs multiple times, but you were getting index of only first STRING and last index of END which will return substring, starts with first STRING to last END.
i.e.
a222 END, and this is STRING b2838
You've already got some good answers but I'll add another that uses ReadOnlyMemory from .NET core. That provides a solution that doesn't allocate new strings which can be nice. C# iterators are a common way to transform one sequence, of chars in this case, into another. This method would be used to transform the input string into sequence of ReadOnlyMemory each containing the tokens your after.
public static IEnumerable<ReadOnlyMemory<char>> Tokenize(string source, string beginPattern, string endPattern)
{
if (string.IsNullOrEmpty(source) ||
string.IsNullOrEmpty(beginPattern) ||
string.IsNullOrEmpty(endPattern))
yield break;
var sourceText = source.AsMemory();
int start = 0;
while (start < source.Length)
{
start = source.IndexOf(beginPattern, start);
if (-1 != start)
{
int end = source.IndexOf(endPattern, start);
if (-1 != end)
{
start += beginPattern.Length;
yield return sourceText.Slice(start, (end - start));
}
else
break;
start = end + endPattern.Length;
}
else
{
break;
}
}
}
Then you'd just call it like so to iterate over the tokens...
static void Main(string[] args)
{
const string Source = "This is STRING a222 END, and this is STRING b2838 END.";
foreach (var token in Tokenize(Source, "STRING", "END"))
{
Console.WriteLine(token);
}
}
string myString = "This is STRING a222 END, and this is STRING b2838 END.";
// Fix the issue based on #PaulF's comment.
if (myString.StartsWith("STRING"))
myString = $"DUMP {myString}";
var arr = myString.Split(new string[] { "STRING", "END" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < arr.Length; i++)
{
if(i%2 > 0)
{
// This is your string
Console.WriteLine(arr[i].Trim());
}
}
I am trying to read a file and split the text after every 1000 characters. But I want to keep the words intact. So it should just split at the space. If the 1000th character is not a space, then split at the first space just before or just after it. Any idea how to do that? I am also removing the extra spaces from the text.
while ((line = file.ReadLine()) != null)
{
text = text + line.Trim();
noSpaceText = Regex.Replace(text, #"\r\n?|\n/", "");
}
List<string> rowsToInsert = new List<string>();
int splitAt = 1000;
for (int i = 0; i < noSpaceText.Length; i = i + splitAt)
{
if (noSpaceText.Length - i >= splitAt)
{
rowsToInsert.Add(noSpaceText.Substring(i, splitAt));
}
else
rowsToInsert.Add(noSpaceText.Substring(i,
((noSpaceText.Length - i))));
}
foreach(var item in rowsToInsert)
{
Console.WriteLine(item);
}
Okay, just typed this non tested solution which should do the trick:
public static List<string> SplitOn(this string input, int charLength, char[] seperator)
{
List<string> splits = new List<string>();
var tokens = input.Split(seperator);
// -1 because first token adds 1 to length
int totalLength = -1;
List<string> segments = new List<string>;
foreach(var t in tokens)
{
if(totalLength + t.Length+1 > charLength)
{
splits.Add(String.Join(" ", segments));
totalLength = -1;
segments.Clear();
}
totalLength += t.Length + 1;
segments.Add(t);
}
if(segments.Count>0)
{
splits.Add(String.Join(" ", segments));
}
return splits;
}
It's an extension Method, which splits an input text in segments by whitespaces, means, i iterate over an array with just words. Then counting the length of each segment, checking for totallength and add it to result list.
An alternate solution:
public static List<string> SplitString(string stringInput, int blockLength)
{
var output = new List<string>();
var count = 0;
while(count < stringInput.Length)
{
string block = "";
if(count + blockLength > stringInput.Length)
{
block = stringInput.Substring(count, stringInput.Length - count);
}
else
{
block = stringInput.Substring(count, blockLength + 1);
}
if(block.Length < blockLength)
{
output.Add(block);
count += block.Length;
}
else if(block.EndsWith(" "))
{
output.Add(block);
count = count+blockLength + 1;
}
else
{
output.Add(block.Substring(0, block.LastIndexOf(" ")));
count = count + block.LastIndexOf(" ") +1;
}
}
return output;
}
I want to break a string up into lines of a specified maximum length, without splitting any words, if possible (if there is a word that exceeds the maximum line length, then it will have to be split).
As always, I am acutely aware that strings are immutable and that one should preferably use the StringBuilder class. I have seen examples where the string is split into words and the lines are then built up using the StringBuilder class, but the code below seems "neater" to me.
I mentioned "best" in the description and not "most efficient" as I am also interested in the "eloquence" of the code. The strings will never be huge, generally splitting into 2 or three lines, and it won't be happening for thousands of lines.
Is the following code really bad?
private static IEnumerable<string> SplitToLines(string stringToSplit, int maximumLineLength)
{
stringToSplit = stringToSplit.Trim();
var lines = new List<string>();
while (stringToSplit.Length > 0)
{
if (stringToSplit.Length <= maximumLineLength)
{
lines.Add(stringToSplit);
break;
}
var indexOfLastSpaceInLine = stringToSplit.Substring(0, maximumLineLength).LastIndexOf(' ');
lines.Add(stringToSplit.Substring(0, indexOfLastSpaceInLine >= 0 ? indexOfLastSpaceInLine : maximumLineLength).Trim());
stringToSplit = stringToSplit.Substring(indexOfLastSpaceInLine >= 0 ? indexOfLastSpaceInLine + 1 : maximumLineLength);
}
return lines.ToArray();
}
Even when this post is 3 years old I wanted to give a better solution using Regex to accomplish the same:
If you want the string to be splitted and then use the text to be displayed you can use this:
public string SplitToLines(string stringToSplit, int maximumLineLength)
{
return Regex.Replace(stringToSplit, #"(.{1," + maximumLineLength +#"})(?:\s|$)", "$1\n");
}
If on the other hand you need a collection you can use this:
public MatchCollection SplitToLines(string stringToSplit, int maximumLineLength)
{
return Regex.Matches(stringToSplit, #"(.{1," + maximumLineLength +#"})(?:\s|$)");
}
NOTES
Remember to import regex (using System.Text.RegularExpressions;)
You can use string interpolation on the match:
$#"(.{{1,{maximumLineLength}}})(?:\s|$)"
The MatchCollection works almost like an Array
Matching example with explanation here
How about this as a solution:
IEnumerable<string> SplitToLines(string stringToSplit, int maximumLineLength)
{
var words = stringToSplit.Split(' ').Concat(new [] { "" });
return
words
.Skip(1)
.Aggregate(
words.Take(1).ToList(),
(a, w) =>
{
var last = a.Last();
while (last.Length > maximumLineLength)
{
a[a.Count() - 1] = last.Substring(0, maximumLineLength);
last = last.Substring(maximumLineLength);
a.Add(last);
}
var test = last + " " + w;
if (test.Length > maximumLineLength)
{
a.Add(w);
}
else
{
a[a.Count() - 1] = test;
}
return a;
});
}
I reworked this as prefer this:
IEnumerable<string> SplitToLines(string stringToSplit, int maximumLineLength)
{
var words = stringToSplit.Split(' ');
var line = words.First();
foreach (var word in words.Skip(1))
{
var test = $"{line} {word}";
if (test.Length > maximumLineLength)
{
yield return line;
line = word;
}
else
{
line = test;
}
}
yield return line;
}
I don't think your solution is too bad. I do, however, think you should break up your ternary into an if else because you are testing the same condition twice. Your code might also have a bug. Based on your description, it seems you want lines <= maxLineLength, but your code counts the space after the last word and uses it in the <= comparison resulting in effectively < behavior for the trimmed string.
Here is my solution.
private static IEnumerable<string> SplitToLines(string stringToSplit, int maxLineLength)
{
string[] words = stringToSplit.Split(' ');
StringBuilder line = new StringBuilder();
foreach (string word in words)
{
if (word.Length + line.Length <= maxLineLength)
{
line.Append(word + " ");
}
else
{
if (line.Length > 0)
{
yield return line.ToString().Trim();
line.Clear();
}
string overflow = word;
while (overflow.Length > maxLineLength)
{
yield return overflow.Substring(0, maxLineLength);
overflow = overflow.Substring(maxLineLength);
}
line.Append(overflow + " ");
}
}
yield return line.ToString().Trim();
}
It is a bit longer than your solution, but it should be more straightforward. It also uses a StringBuilder so it is much faster for large strings. I performed a benchmarking test for 20,000 words ranging from 1 to 11 characters each split into lines of 10 character width. My method completed in 14ms compared to 1373ms for your method.
Try this (untested)
private static IEnumerable<string> SplitToLines(string value, int maximumLineLength)
{
var words = value.Split(' ');
var line = new StringBuilder();
foreach (var word in words)
{
if ((line.Length + word.Length) >= maximumLineLength)
{
yield return line.ToString();
line = new StringBuilder();
}
line.AppendFormat("{0}{1}", (line.Length>0) ? " " : "", word);
}
yield return line.ToString();
}
~6x faster than the accepted answer
More than 1.5x faster than the Regex version in Release Mode (dependent on line length)
Optionally keep the space at the end of the line or not (the regex version always keeps it)
static IEnumerable<string> SplitToLines(string stringToSplit, int maximumLineLength, bool removeSpace = true)
{
int start = 0;
int end = 0;
for (int i = 0; i < stringToSplit.Length; i++)
{
char c = stringToSplit[i];
if (c == ' ' || c == '\n')
{
if (i - start > maximumLineLength)
{
string substring = stringToSplit.Substring(start, end - start); ;
start = removeSpace ? end + 1 : end; // + 1 to remove the space on the next line
yield return substring;
}
else
end = i;
}
}
yield return stringToSplit.Substring(start); // remember last line
}
Here is the example code used to test speeds (again, run on your own machine and test in Release mode to get accurate timings)
https://dotnetfiddle.net/h5I1GC
Timings on my machine in release mode .Net 4.8
Accepted Answer: 667ms
Regex: 368ms
My Version: 117ms
My requirement was to have a line break at the last space before the 30 char limit.
So here is how i did it. Hope this helps anyone looking.
private string LineBreakLongString(string input)
{
var outputString = string.Empty;
var found = false;
int pos = 0;
int prev = 0;
while (!found)
{
var p = input.IndexOf(' ', pos);
{
if (pos <= 30)
{
pos++;
if (p < 30) { prev = p; }
}
else
{
found = true;
}
}
outputString = input.Substring(0, prev) + System.Environment.NewLine + input.Substring(prev, input.Length - prev).Trim();
}
return outputString;
}
An approach using recursive method and ReadOnlySpan (Tested)
public static void SplitToLines(ReadOnlySpan<char> stringToSplit, int index, ref List<string> values)
{
if (stringToSplit.IsEmpty || index < 1) return;
var nextIndex = stringToSplit.IndexOf(' ');
var slice = stringToSplit.Slice(0, nextIndex < 0 ? stringToSplit.Length : nextIndex);
if (slice.Length <= index)
{
values.Add(slice.ToString());
nextIndex++;
}
else
{
values.Add(slice.Slice(0, index).ToString());
nextIndex = index;
}
if (stringToSplit.Length <= index) return;
SplitToLines(stringToSplit.Slice(nextIndex), index, ref values);
}
I am using the following C# code to modify a lowercase letter to uppercase after a single quote:
public virtual string FirstName
{
get { return _firstName; }
set
{
if (value != null)
{
int pos = value.IndexOf("'", 0);
int strlength = value.Length - 1;
if (pos >= 0 && pos != strlength)
{
string temp = value[pos + 1].ToString();
temp = temp.ToUpper();
value = value.Remove(pos + 1, 1);
value = value.Insert(pos + 1, temp);
}
}
}
}
To me this looks like overkill. Is there an easier way to achieve the desired result:
Value: Mc'donald
Expected: Mc'Donald
here is without regex
int pos = data.IndexOf("'");
if (pos >= 0 && pos < data.Length - 1)
{
StringBuilder sbl = new StringBuilder(data);
sbl[pos + 1] = char.ToUpper(sbl[pos + 1]);
data = sbl.ToString();
}
Since you're open to Regex, would this overload of the Regex.Replace do what you need?
Regex.Replace Method (String, MatchEvaluator)
Here's a modified version of the example given at the link above. I've changed it to use the '\w pattern and to return the match in upper case.
using System;
using System.Text.RegularExpressions;
class RegExSample
{
static string CapText(Match m)
{
// Return the match in upper case
return m.ToString().ToUpperInvariant();
}
static void Main()
{
string text = "Mc'donald";
System.Console.WriteLine("text=[" + text + "]");
Regex rx = new Regex(#"'\w");
string result = rx.Replace(text, new MatchEvaluator(RegExSample.CapText));
System.Console.WriteLine("result=[" + result + "]");
}
}
Perhaps regular expressions?
string value = "Mc'donald";
string found = Regex.Match(value, "'[\\w]").Value;
string result = value.Replace(found, found.ToUpper());
Console.WriteLine(result); // Mc'Donald
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;
}