C# replace part of string but only exact matches possible? - c#

I have a string beginString = "apple|fruitsapple|turnip";
What I want to do is replace just apple with mango, not fruitsapple.
string fixedString = beginString.Replace("apple","mango"); This doesn't work because it replaces both apple and fruitsapple.
Any ideas?

beginString = "|" + beginString + "|";
fixedString = beginString.Replace("|apple|","|mango|");

This cannot be done in the way you have said since it will consider the entire string to be a string. You can do the split by | as you have used or else have the strings in a list and use equals and then replace it.
String[] words = beginString.Split("|");
now do the replace on words. works for any scenario.

The variation on other answers in LINQ style:
string fixedString = string.Join("|",
beginString
.Split('|')
.Select(s => s != "apple" ? s : "mango"));

Closest I can get. Was gonna suggest regular expression, but that won't always work as you want. You have to split the string first and then remake it.
string searchString = "apple";
string newString = "mango";
string beginString = "apple|fruitsapple|turnip";
string[] array = beginString.Split('|');
foreach (var item in array)
{
if (item == searchString)
item.Replace(searchString, newString);
}
string recreated = "";
new List<string>(array).ForEach(e => recreated += e + "|");
recreated.TrimEnd('|');

string newstr = Regex.Replace("apple|fruitsapple|turnip", #"\bapple\b", "mango");

Related

Remove characters from a specific index character

I would like to know how can i remove characters in a string from a specific index like :
string str = "this/is/an/example"
I want to remove all characters from the third '/' including so it would be like this:
str = "this/is/an"
I tried with substring and regex but i cant find a solution.
Using string operations:
str = str.Substring(0, str.IndexOf('/', str.IndexOf('/', str.IndexOf('/') + 1) + 1));
Using regex:
str = Regex.Replace(str, #"^(([^/]*/){2}[^/]*)/.*$", "$1");
To get "this/is/an":
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/'));
If you need to keep the slash:
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/')+1);
This expects there to be at least one slash. If none are present, you should check it beforehand to not throw an exception:
string str = "this.s.an.example";
string newStr = str;
if (str.Contains('/'))
newStr = str.Remove(str.LastIndexOf('/'));
If its importaint to get the third one, make a dynamic method for it, like this. Input the string, and which "folder" you want returned. 3 in your example will return "this/is/an":
static string ReturnNdir(string sDir, int n)
{
while (sDir.Count(s => s == '/') > n - 1)
sDir = sDir.Remove(sDir.LastIndexOf('/'));
return sDir;
}
This regex is the answer: ^[^/]*\/[^/]*\/[^/]*. It will capture the first three chunks.
var regex = new Regex("^[^/]*\\/[^/]*\\/[^/]*", RegexOptions.Compiled);
var value = regex.Match(str).Value;
I think the best way of doing that it's creating a extension
string str = "this/is/an/example";
str = str.RemoveLastWord();
//specifying a character
string str2 = "this.is.an.example";
str2 = str2.RemoveLastWord(".");
With this static class:
public static class StringExtension
{
public static string RemoveLastWord(this string value, string separator = "")
{
if (string.IsNullOrWhiteSpace(value))
return string.Empty;
if (string.IsNullOrWhiteSpace(separator))
separator = "/";
var words = value.Split(Char.Parse(separator));
if (words.Length == 1)
return value;
value = string.Join(separator, words.Take(words.Length - 1));
return value;
}
}

Retrieving string from a string which is in between two String?

i have a string Like
"Hello i want to go."
my code give "want to go."
but i need string between " i " and " to " how can i get this? my code is as below.
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
string input = "Hello i want to go.";
Regex regex = new Regex(#".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
result = match.Groups[1].Value;
}
This regex will match any 'word' between 'i' (not case sensitive) and 'to'.
EDIT: changed ...to.* => to\s.* as suggested in the comments.
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
If you want the word after the "i" then:
string result = input.Split(" i ")[1].Split(" ")[0];
Use
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
just do it with one simple line of code
var word = "Hello i want to go.".Split(' ')[2];
//Returns the word "want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
Here's an example using Regex which gives you the index of each occurrence of "want":
string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");
while(match.Success){
Console.WriteLine(string.Format("Index: {0}", match.Index));
match = match.NextMatch();
}
Nowhere does it say Regex...
string result = input.Split.Skip(2).Take(1).First()
it's work
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
and it can be called as
string respons = Between("Hello i want to go."," i "," to ");
it return want

How to split string using Substring

I have a string like '/Test1/Test2', and i need to take Test2 separated from the same. How can i do that in c# ?
Try this:
string toSplit= "/Test1/Test2";
toSplit.Split('/');
or
toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries);
to split, the latter will remove the empty string.
Adding .Last() will get you the last item.
e.g.
toSplit.Split('/').Last();
Use .Split().
string foo = "/Test1/Test2";
string extractedString = foo.Split('/').Last(); // Result Test2
This site have quite a few examples of splitting strings in C#. It's worth a read.
Using .Split and a little bit of LINQ, you could do the following
string str = "/Test1/Test2";
string desiredValue = str.Split('/').Last();
Otherwise you could do
string str = "/Test1/Test2";
string desiredValue = str;
if(str.Contains("/"))
desiredValue = str.Substring(str.LastIndexOf("/") + 1);
Thanks Binary Worrier, forgot that you'd want to drop the '/', darn fenceposts
string[] arr = string1.split('/');
string result = arr[arr.length - 1];
string [] split = words.Split('/');
This will give you an array split that will contain "", "Test1" and "Test2".
If you just want the Test2 portion, try this:
string fullTest = "/Test1/Test2";
string test2 = test.Split('/').ElementAt(1); //This will grab the second element.
string inputString = "/Test1/Test2";
string[] stringSeparators = new string[] { "/Test1/"};
string[] result;
result = inputString.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write("{0}",s);
}
OUTPUT : Test2

Using LINQ to strip a suffix from a string if it contains a suffix in a list?

How can I strip a suffix from a string, and return it, using C#/LINQ? Example:
string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" };
string myString = "DeleteItemMessagePlural";
string stringWithoutSuffix = myString.???; // what do I do here?
// stringWithoutSuffix == "DeleteItemMessage"
var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();
if (firstMatchingSuffix != null)
myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));
You need to build a regular expression from the list:
var regex = new Regex("(" + String.Join("|", list.Select(Regex.Escape)) + ")$");
string stringWithoutSuffix = regex.Replace(myString, "");
// Assuming there is exactly one matching suffix (this will check that)
var suffixToStrip = suffixes.Single(x => myString.EndsWith(x));
// Replace the matching one:
var stringWithoutSuffix = Regex.Replace(myString, "(" +suffixToStrip + ")$", "");
OR, since you know the length of the matching suffix:
// Assuming there is exactly one matching suffix (this will check that)
int trim = suffixes.Single(x => myString.EndsWith(x)).Length;
// Remove the matching one:
var stringWithoutSuffix = myString.Substring(0, myString.Length - trim);

How to trim whitespace between characters

How to remove whitespaces between characters in c#?
Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".
But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?
You could use String.Replace method
string str = "C Sharp";
str = str.Replace(" ", "");
or if you want to remove all whitespace characters (space, tabs, line breaks...)
string str = "C Sharp";
str = Regex.Replace(str, #"\s", "");
If you want to keep one space between every word. You can do it this way as well:
string.Join(" ", inputText.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => x.Trim()));
Use String.Replace to replace all white space with nothing.
eg
string newString = myString.Replace(" ", "");
if you want to remove all spaces in one word:
input.Trim().Replace(" ","")
And If you want to remove extra spaces in the sentence, you should use below:
input.Trim().Replace(" +","")
the regex " +", would check if there is one ore more following space characters in the text and replace them with one space.
If you want to keep one space between every word. this should do it..
public static string TrimSpacesBetweenString(string s)
{
var mystring =s.RemoveTandNs().Split(new string[] {" "}, StringSplitOptions.None);
string result = string.Empty;
foreach (var mstr in mystring)
{
var ss = mstr.Trim();
if (!string.IsNullOrEmpty(ss))
{
result = result + ss+" ";
}
}
return result.Trim();
}
it will remove the string in between the string
so if the input is
var s ="c sharp";
result will be "c sharp";
//Remove spaces from a string just using substring method and a for loop
static void Main(string[] args)
{
string businessName;
string newBusinessName = "";
int i;
Write("Enter a business name >>> ");
businessName = ReadLine();
for(i = 0; i < businessName.Length; i++)
{
if (businessName.Substring(i, 1) != " ")
{
newBusinessName += businessName.Substring(i, 1);
}
}
WriteLine("A cool web site name could be www.{0}.com", newBusinessName);
}
var str=" c sharp "; str = str.Trim();
str = Regex.Replace(str, #"\s+", " "); ///"c sharp"
string myString = "C Sharp".Replace(" ", "");
I found this method great for doing things like building a class that utilizes a calculated property to take lets say a "productName" and stripping the whitespace out to create a URL that will equal an image that uses the productname with no spaces. For instance:
namespace XXX.Models
{
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductImage
{
get { return ProductName.Replace(" ", string.Empty) + ".jpg"; }
}
}
}
So in this answer I have used a very similar method as w69rdy, but used it in an example, plus I used string.Empty instead of "". And although after .Net 2.0 there is no difference, I find it much easier to read and understand for others who might need to read my code. I also prefer this because I sometimes get lost in all the quotes I might have in a code block.

Categories

Resources