C#: How to Delete the matching substring between 2 strings? - c#

If I have two strings ..
say
string1="Hello Dear c'Lint"
and
string2="Dear"
.. I want to Compare the strings first and delete the matching substring .. the result of the above string pairs is:
"Hello c'Lint"
(i.e, two spaces between "Hello" and "c'Lint") for simplicity, we'll assume that string2 will be the sub-set of string1 .. (i mean string1 will contain string2)..

What about
string result = string1.Replace(string2,"");
EDIT: I saw your updated question too late :)
An alternative solution to replace only the first occurrence using Regex.Replace, just for curiosity:
string s1 = "Hello dear Alice and dear Bob.";
string s2 = "dear";
bool first = true;
string s3 = Regex.Replace(s1, s2, (m) => {
if (first) {
first = false;
return "";
}
return s2;
});

Do this only:
string string1 = textBox1.Text;
string string2 = textBox2.Text;
string string1_part1=string1.Substring(0, string1.IndexOf(string2));
string string1_part2=string1.Substring(
string1.IndexOf(string2)+string2.Length, string1.Length - (string1.IndexOf(string2)+string2.Length));
string1 = string1_part1 + string1_part2;
Hope it helps. It will remove only first occurance.

you would probably rather want to try
string1 = string1.Replace(string2 + " ","");
Otherwise you will end up with 2 spaces in the middle.

string1.Replace(string2, "");
Note that this will remove all occurences of string2 within string1.

Off the top of my head, removing the first instance could be done like this
var sourceString = "1234412232323";
var removeThis = "23";
var a = sourceString.IndexOf(removeThis);
var b = string.Concat(sourceString.Substring(0, a), sourceString.Substring(a + removeThis.Length));
Please test before releasing :o)

Try This One only one line code...
string str1 = tbline.Text;
string str2 = tbsubstr.Text;
if (tbline.Text == "" || tbsubstr.Text == "")
{
MessageBox.Show("Please enter a line and also enter sunstring text in textboo");
}
else
{
**string delresult = str1.Replace(str2, "");**
tbresult.Text = delresult;
}**

Related

String Replacement C#

Hope you can give me some light on this:
I have this var
string TestString = "KESRNAN FOREST S BV";
I want to replace the S that is alone, so I tried with the following
public static string FixStreetName(string streetName)
{
string result = "";
string stringToCheck = streetName.ToUpper();
// result = stringToCheck.Replace(StreetDirection(stringToCheck), "").Replace(StreetType(stringToCheck),"").Trim();
result = stringToCheck.Replace("S", "").Replace("BV", "").Trim();
return result;
}
But this is replacing all S on that string. any ideas?
Use regular expressions,
\b
denotes word boundaries. here is an example on C# Pad
string x = "KESRNAN FOREST S BV";
var result = System.Text.RegularExpressions.Regex.Replace(x, #"\bS\b", "");
Console.WriteLine(result);
If you can easily identify certain "delimiter" characters, one possibility is to 1. split your input string into several parts using string.Split; then 2. pick the parts that you want, and finally 3. "glue" them back together using string.Join:
var partsToExclude = new string[] { "S", "BV" };
/* 1. */ var parts = stringToCheck.Split(' ');
/* 2. */ var selectedParts = parts.Where(part => !partsToExclude.Contains(part));
/* 3. */ return string.Join(" ", selectedParts.ToArray());
Using Regex:
string input = "S KESRNAN FOREST S BV S";
string result = Regex.Replace(input, #"\b(S)", "");
As you can see alone S is before a space " ". In the other word have this string "S " which want to replace it.
Try this :
string TestString = "KESRNAN FOREST S BV";
string replacement = TestString.Replace("S ", "");
Another way of doing what you want:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string testString = "S KESRNAN S FOREST BV S";
// deleting S in middle of string
for (int i = 1; i < testString.Length-1; i++)
{
if (testString[i]=='S'&&testString[i-1]==' '&&testString[i+1]==' ')
testString=testString.Remove(i,2);
}
// deleting S in the begining of string
if (testString.StartsWith("S "))
testString = testString.Remove(0, 2);
// deleting S at the end of string
if (testString.EndsWith(" S"))
testString = testString.Remove(testString.Length-2, 2);
Console.WriteLine(testString);
}
}
}

How do I replace word in string except first occurrence using c#

How do I replace word in string except first occurrence using c#
for example
string s= "hello my name is hello my name hello";
replace hello with x
output should be string news = "hello my name is x my name x";
I tried like works fine
string originalStr = "hello my hello ditch hello";
string temp = "hello";
string str = originalStr.Substring(0, originalStr.IndexOf(temp) + temp.Length);
originalStr = str + originalStr.Substring(str.Length).Replace(temp, "x");
can I have Regex expression for above code ?
This will do it for a general pattern:
var matchPattern = Regex.Escape("llo");
var replacePattern = string.Format("(?<={0}.*){0}", matchPattern);
var regex = new Regex(replacePattern);
var newText = regex.Replace("hello llo llo", "x");
If you want to only match and replace whole words, edit your pattern accordingly:
var matchPattern = #"\b" + Regex.Escape("hello") + #"\b";
Try this:
string pat = "hello";
string tgt = "x";
string tmp = s.Substring(s.IndexOf(pat)+pat.Length);
s = s.Replace(tmp, tmp.Replace(pat,tgt));
tmp is the substring of the original string starting after the end of first occurrence of the pattern to be replaced (pat). We then replace pat with the desired value (tgt) within this substring, and replace the substring in the original string with this updated value.
Demo
Do you need regex? You could use this little LINQ query and String.Join:
int wordCount = 0;
var newWords = s.Split()
.Select(word => word != "hello" || ++wordCount == 1 ? word : "x");
string newText = string.Join(" ", newWords);
But note that this will replace all white-spaces (even tabs or newlines) with a space.

All elements before last comma in a string in c#

How can i get all elements before comma(,) in a string in c#?
For e.g.
if my string is say
string s = "a,b,c,d";
then I want all the element before d i.e. before the last comma.So my new string shout look like
string new_string = "a,b,c";
I have tried split but with that i can only one particular element at a time.
string new_string = s.Remove(s.LastIndexOf(','));
If you want everything before the last occurrence, use:
int lastIndex = input.LastIndexOf(',');
if (lastIndex == -1)
{
// Handle case with no commas
}
else
{
string beforeLastIndex = input.Substring(0, lastIndex);
...
}
Use the follwoing regex: "(.*),"
Regex rgx = new Regex("(.*),");
string s = "a,b,c,d";
Console.WriteLine(rgx.Match(s).Groups[1].Value);
You can also try:
string s = "a,b,c,d";
string[] strArr = s.Split(',');
Array.Resize(strArr, Math.Max(strArr.Length - 1, 1))
string truncatedS = string.join(",", strArr);

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

I am trying to persist string from an ASP.NET textarea. I need to strip out the carriage return line feeds and then break up whatever is left into a string array of 50 character pieces.
I have this so far
var commentTxt = new string[] { };
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb != null)
commentTxt = cmtTb.Text.Length > 50
? new[] {cmtTb.Text.Substring(0, 50), cmtTb.Text.Substring(51)}
: new[] {cmtTb.Text};
It works OK, but I am not stripping out the CrLf characters. How do I do this correctly?
You could use a regex, yes, but a simple string.Replace() will probably suffice.
myString = myString.Replace("\r\n", string.Empty);
The .Trim() function will do all the work for you!
I was trying the code above, but after the "trim" function, and I noticed it's all "clean" even before it reaches the replace code!
String input: "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."
Source: http://www.dotnetperls.com/trim
This splits the string on any combo of new line characters and joins them with a space, assuming you actually do want the space where the new lines would have been.
var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";
var newString = string.Join(" ", Regex.Split(oldString, #"(?:\r\n|\n|\r)"));
Console.Write(newString);
// prints:
// the quick brown fox jumped over the box and landed on some rocks.
Nicer code for this:
yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);
Here is the perfect method:
Please note that Environment.NewLine works on on Microsoft platforms.
In addition to the above, you need to add \r and \n in a separate function!
Here is the code which will support whether you type on Linux, Windows, or Mac:
var stringTest = "\r Test\nThe Quick\r\n brown fox";
Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");
stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);
Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();
Try this:
private void txtEntry_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string trimText;
trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
this.txtEntry.Text = trimText;
btnEnter.PerformClick();
}
}
Assuming you want to replace the newlines with something so that something like this:
the quick brown fox\r\n
jumped over the lazy dog\r\n
doesn't end up like this:
the quick brown foxjumped over the lazy dog
I'd do something like this:
string[] SplitIntoChunks(string text, int size)
{
string[] chunk = new string[(text.Length / size) + 1];
int chunkIdx = 0;
for (int offset = 0; offset < text.Length; offset += size)
{
chunk[chunkIdx++] = text.Substring(offset, size);
}
return chunk;
}
string[] GetComments()
{
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb == null)
{
return new string[] {};
}
// I assume you don't want to run the text of the two lines together?
var text = cmtTb.Text.Replace(Environment.Newline, " ");
return SplitIntoChunks(text, 50);
}
I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.
Use:
string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));
Use double \ or use # before " for find \r or \n
htmlStr = htmlStr.Replace("\\r", string.Empty).Replace("\\n", string.Empty);
htmlStr = htmlStr.Replace(#"\r", string.Empty).Replace(#"\n", string.Empty);

remove last word in label split by \

Ok i have a string where i want to remove the last word split by \
for example:
string name ="kak\kdk\dd\ddew\cxz\"
now i want to remove the last word so that i get a new value for name as
name= "kak\kdk\dd\ddew\"
is there an easy way to do this
thanks
How do you get this string in the first place? I assume you know that '' is the escape character in C#. However, you should get far by using
name = name.TrimEnd('\\').Remove(name.LastIndexOf('\\') + 1);
string result = string.Join("\\",
"kak\\kdk\\dd\\ddew\\cxz\\"
.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Reverse()
.Skip(1)
.Reverse()
.ToArray()) + "\\";
Here's a non-regex manner of doing it.
string newstring = name.SubString(0, name.SubString(0, name.length - 1).LastIndexOf('\\'));
This regex replacement should do the trick:
name = Regex.Replace(name, #"\\[a-z]*\\$", "\\");
Try this:
const string separator = "\\";
string name = #"kak\kdk\dd\ddew\cxz\";
string[] names = name.Split(separator.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(separator, names, 0, names.Length - 1) + separator;
EDIT:I just noticed that name.Substring(0,x) is equivalent to name.Remove(x), so I've changed my answer to reflect that.
In a single line:
name = name = name.Remove(name.Remove(name.Length - 1).LastIndexOf('\\') + 1);
If you want to understand it, here's how it might be written out (overly) verbosely:
string nameWithoutLastSlash = name.Remove(name.Length - 1);
int positionOfNewLastSlash = nameWithoutLastSlash.LastIndexOf('\\') + 1;
string desiredSubstringOfName = name.Remove(positionOfNewLastSlash);
name = desiredSubstringOfName;
My Solution
public static string RemoveLastWords(this string input, int numberOfLastWordsToBeRemoved, char delimitter)
{
string[] words = input.Split(new[] { delimitter });
words = words.Reverse().ToArray();
words = words.Skip(numberOfLastWordsToBeRemoved).ToArray();
words = words.Reverse().ToArray();
string output = String.Join(delimitter.ToString(), words);
return output;
}
Function call
RemoveLastWords("kak\kdk\dd\ddew\cxz\", 1, '\')
string name ="kak\kdk\dd\ddew\cxz\"
string newstr = name.TrimEnd(#"\")
if you working with paths:
string name = #"kak\kdk\dd\ddew\cxz\";
Path.GetDirectoryName(name.TrimEnd('\\'));
//ouput: kak\kdk\dd\ddew
string[] temp = name.Split('\\');
string last = "\\" + temp.Last();
string target = name.Replace(last, "");
For Linq-lovers: With later C# versions you can use SkipLast together with Split and string.Join:
var input = #"kak\kdk\dd\ddew\cxz\";
string result = string.Join( #"\", input
.Split( #"\", StringSplitOptions.RemoveEmptyEntries )
.SkipLast( 1 ))
+ #"\";

Categories