Having an issue with trimming a string in C# [duplicate] - c#

This question already has answers here:
Get string between two strings in a string
(27 answers)
Closed 7 years ago.
I have a problem about trimming below word in C#
For example, I got a string = "StackLevelTwoItem" and I need to pull the "Two" or "Three" out of this string.
StackLevelTwoItem -> I should get "Two"
StackLevelThreeItem -> I should get "Three"
... and so on ...
Can anybody help?
Thank you

For the two examples given:
const string prefix = "StackLevel";
const string suffix = "Item";
public static string GetCentralPart(string str)
{
if (str == null)
{
return str;
}
if (!str.StartsWith(prefix) || !str.EndsWith(suffix))
{
return str;
}
return str.Substring(prefix.Length, str.Length - prefix.Length - suffix.Length);
}
Use:
string str = "StackLevelThreeItem";
string centralPart = GetCentralPart(str);
The code is quite linear... The only interesting points are the use of some const string for the prefix/suffix, the use of StartsWith/EndsWith to check that the string really has the prefix/suffix, and how the Substring length is calculated.

i would use RegEx for this Case
string Result = Regex.Match("StackLevelOneItem", #"(?<=StackLevel)[\w]*(?=Item)").Value;

Here is an example using Regex.
static void Main(string[] args)
{
var l2 = GetLevel("StackLevelTwoItem"); // returns "Two"
var l3 = GetLevel("StackLevelThreeItem"); // returns "Three"
var l1 = GetLevel("StackLvlOneItem"); // returns empty string
}
static string GetLevel(string input)
{
var pattern = "StackLevel(.*)Item";
var match = Regex.Match(input, pattern);
if (match.Groups[1].Success)
return match.Groups[1].Value;
else
return String.Empty;
}

Related

C# Getting value between two same characters

Usually, we can easily get a String value between two characters. My question is, how do I get the value between two same characters.
For example:
String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";
In this example, how can I extract the value 9367119 from the entire string?
The solution that I use doesn't work since 9367119 has the same / characters to the right and left of it.
Here's what I have so far:
This works for values that doesn't have two same characters to the left and right. Such as: /dog\ I can easily replace / and \ with my solution
public static string Between(string full_value, string a, string b)
{
int posA = full_value.IndexOf(a);
int posB = full_value.LastIndexOf(b);
if (posA == -1)
{
return "";
}
if (posB == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= posB)
{
return "";
}
return full_value.Substring(adjustedPosA, posB - adjustedPosA);
}
You could just Split and get the relevant part:
string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
string[] sp = s.Split('/');
Console.WriteLine(sp[4]);
IdeOne demo.
Use following regex:
(?<=/)\d+(?=/)
String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";
var matches = Regex.Matches(full_value, #"(?<=/)\d+(?=/)");
try this way use Split
string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
string[] sps = s.Split('/');
foreach(string sp in sps ){
if(sp =="9367119"){
Console.WriteLine(sp);
}
}

How to get a word in string C#

Given :
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
How can I get the word "CP1" and "1" from 'SSA1' in command and for command_2 is "CP1" and "MPS" then set to another variables?
I already search the similar question but still not found the best answer.
Edited :
For command variable, I want get 'CP1' from CP1 and '1' from SSA1. And for command_2 variable I want get 'CP1' from CP1 and 'MPS' from MPS.
You just need to get strings between angled brackets.. then you just replace "SSA" with "" and you have all the words you wanted !!!
using System.IO;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Program
{
static void Main()
{
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
prnt(command);
prnt(command_2);
//prnt(command+command_2); //even this will work :)
}
private static void prnt(string str)
{
List<string> l = ExtractFromString(str,"<",">");
foreach(string ll in l)
Console.WriteLine(ll.Replace("SSA",""));
}
private static List<string> ExtractFromString(string text, string start, string end)
{
List<string> Matched = new List<string>();
int index_start = 0, index_end=0;
bool exit = false;
while(!exit)
{
index_start = text.IndexOf(start);
index_end = text.IndexOf(end);
if (index_start != -1 && index_end != -1)
{
Matched.Add(text.Substring(index_start + start.Length, index_end - index_start - start.Length));
text = text.Substring(index_end + end.Length);
}
else
exit = true;
}
return Matched;
}
}
Output:
CP1
1
CP1
MPS
Source of Extract method: Extract all strings between two strings
You're parsing XML, use XElement classes instead. Then use String or Regex classes to parse tag string content.
this is the code:
string s1 = "<CP1><SSA1>";
int start = s1.IndexOf("<CP");
int end = s1.IndexOf(">"); string
numString = s1.Substring(start + 3, end-start-3); // get the 1
start = s1.IndexOf("<SSA");
end = s1.Length-1;
numString = s1.Substring(start + 4, end - start - 4); // get the 1
with this code you should receive the numbers after your token, it's doesn't matter how much digits it contain.
To convert the string to int use Parse function, like this: int.Parse(numString)
Same answer to the second string
#Chuki2
I dont know what exactly you want to achieve.. but it could be a way to do this.. check it out below..!!
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
command = command.Replace("<", "#").Replace(">", "#");
command_2 = command_2.Replace("<", "#").Replace(">", "#");
string[] val = command.Split(
new char[]{'#'},
StringSplitOptions.RemoveEmptyEntries
);
string[] val_2 = command_2.Split(
new char[] { '#' },
StringSplitOptions.RemoveEmptyEntries
);
//now because you want to get the only "1" from "SSA1"
//well i dont know what really you want to do but it could be one way to do this.
string lastParameter = val[val.Length-1];
val[val.Length - 1] = lastParameter.Substring(lastParameter.Length - 1);
Another way:
string[] parts = command.Split(new char[] {'<', '>'},StringSplitOptions.RemoveEmptyEntries);
string part1 = parts[0];
string part2 = parts[1].StartsWith("SSA") : parts[1].Substring(3) : parts[1];

First Character of String Lowercase - C# [duplicate]

This question already has answers here:
BestPractice - Transform first character of a string into lower case
(13 answers)
Closed 9 years ago.
How can I make the first character of a string lowercase?
For example: ConfigService
And I need it to be like this: configService
This will work:
public static string? FirstCharToLowerCase(this string? str)
{
if ( !string.IsNullOrEmpty(str) && char.IsUpper(str[0]))
return str.Length == 1 ? char.ToLower(str[0]).ToString() : char.ToLower(str[0]) + str[1..];
return str;
}
(This code arranged as "C# Extension method")
Usage:
myString = myString.FirstCharToLowerCase();
One way:
string newString = oldString;
if (!String.IsNullOrEmpty(newString))
newString = Char.ToLower(newString[0]) + newString.Substring(1);
For what it's worth, an extension method:
public static string ToLowerFirstChar(this string input)
{
if(string.IsNullOrEmpty(input))
return input;
return char.ToLower(input[0]) + input.Substring(1);
}
Usage:
string newString = "ConfigService".ToLowerFirstChar(); // configService
You could try this:
lower = source.Substring(0, 1).ToLower() + source.Substring(1);
string FirstLower(string s)
{
if(string.IsNullOrEmpty(s))
return s;
return s[0].ToString().ToLower() + s.Substring(1);
}
Use this function:
public string GetStringWithFirstCharLowerCase(string value)
{
if (value == null) throw new ArgumentNullException("value")
if (String.IsNullOrWhiteSpace(value)) return value;
char firstChar = Char.ToLowerInvariant(value[0]);
if (value.Length == 1) return firstChar;
return firstChar + value.Substring(1);
}
Please note that further overloading will be necessary if support for other languages is required.
public static string Upper_To_Lower(string text)
{
if (Char.IsUpper(text[0]) == true) { text = text.Replace(text[0], char.ToLower(text[0])); return text; }
return text;
}
public static string Lower_To_Upper(string text)
{
if (Char.IsLower(text[0]) == true) { text = text.Replace(text[0], char.ToUpper(text[0])); return text; }
return text;
}
Hope this will help you ! here i made two methods taking as parameter any string and return the string with the first letter uppercase or lowercase according to the method you will use
string test = "ConfigService";
string result = test.Substring(0, 1).ToLower() + test.Substring(1);
I would simply do this:
Char.ToLowerInvariant(yourstring[0]) + yourstring.Substring(1)
Simple and gets the job done.
EDIT:
Looks like this thread had the same idea. :)
This can help you,changes first character to lower if it is upper and also checks for null or empty and only whitespace string:
string str = "ConfigService";
string strResult = !string.IsNullOrWhiteSpace(str) && char.IsUpper(str, 0) ? str.Replace(str[0],char.ToLower(str[0])) : str;

c# if String Contains 2 "hallo" [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How would you count occurences of a string within a string (C#)?
I want to check if a String contains 2 things..
String hello = "hellohelloaklsdhas";
if hello.Contains(*hello 2 Times*); -> True
How can I solve this?
You could use a regex :)
return Regex.Matches(hello, "hello").Count == 2;
This matches the string hello for the pattern "hello" and returns true if the count is 2.
Regular expressions.
if (Regex.IsMatch(hello,#"(.*hello.*){2,}"))
I guess you meant "hello", and this will match a string with at least 2 "hello" (not exactly 2 "hello")
public static class StringExtensions
{
public static int Matches(this string text, string pattern)
{
int count = 0, i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
}
class Program
{
static void Main()
{
string s1 = "Sam's first name is Sam.";
string s2 = "Dot Net Perls is about Dot Net";
string s3 = "No duplicates here";
string s4 = "aaaa";
Console.WriteLine(s1.Matches("Sam")); // 2
Console.WriteLine(s1.Matches("cool")); // 0
Console.WriteLine(s2.Matches("Dot")); // 2
Console.WriteLine(s2.Matches("Net")); // 2
Console.WriteLine(s3.Matches("here")); // 1
Console.WriteLine(s3.Matches(" ")); // 2
Console.WriteLine(s4.Matches("aa")); // 2
}
}
You can use a regex, and check the length of the result of Matches function. If it's two you win.
new Regex("hello.*hello").IsMatch(hello)
or
Regex.IsMatch(hello, "hello.*hello")
If you use a regular expression MatchCollection you can get this easily:
MatchCollection matches;
Regex reg = new Regex("hello");
matches = reg.Matches("hellohelloaklsdhas");
return (matches.Count == 2);
IndexOf
You can use the IndexOf method to get the index of a certain string. This method has an overload that accepts a starting point, from where to look. When the specified string is not found, -1 is returned.
Here is an example that should speak for itself.
var theString = "hello hello bye hello";
int index = -1;
int helloCount = 0;
while((index = theString.IndexOf("hello", index+1)) != -1)
{
helloCount++;
}
return helloCount==2;
Regex
Another way to get the count is to use Regex:
return (Regex.Matches(hello, "hello").Count == 2);
IndexOf:
int FirstIndex = str.IndexOf("hello");
int SecondIndex = str.IndexOf("hello", FirstIndex + 1);
if(FirstIndex != -1 && SecondIndex != -1)
{
//contains 2 or more hello
}
else
{
//contains not
}
or if you want exactly 2: if(FirstIndex != -1 && SecondIndex != -1 && str.IndexOf("hello", SecondIndex) == -1)

String.Replace ignoring case

I have a string called "hello world"
I need to replace the word "world" to "csharp"
for this I use:
string.Replace("World", "csharp");
but as a result, I don't get the string replaced. The reason is case sensitiveness. The original string contains "world" whereas I'm trying to replace "World".
Is there any way to avoid this case sensitiveness in string.Replace method?
You could use a Regex and perform a case insensitive replace:
class Program
{
static void Main()
{
string input = "hello WoRlD";
string result =
Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
Console.WriteLine(result); // prints "hello csharp"
}
}
var search = "world";
var replacement = "csharp";
string result = Regex.Replace(
stringToLookInto,
Regex.Escape(search),
replacement.Replace("$","$$"),
RegexOptions.IgnoreCase
);
The Regex.Escape is useful if you rely on user input which can contains Regex language elements
Update
Thanks to comments, you actually don't have to escape the replacement string.
Here is a small fiddle that tests the code:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var tests = new[] {
new { Input="abcdef", Search="abc", Replacement="xyz", Expected="xyzdef" },
new { Input="ABCdef", Search="abc", Replacement="xyz", Expected="xyzdef" },
new { Input="A*BCdef", Search="a*bc", Replacement="xyz", Expected="xyzdef" },
new { Input="abcdef", Search="abc", Replacement="x*yz", Expected="x*yzdef" },
new { Input="abcdef", Search="abc", Replacement="$", Expected="$def" },
};
foreach(var test in tests){
var result = ReplaceCaseInsensitive(test.Input, test.Search, test.Replacement);
Console.WriteLine(
"Success: {0}, Actual: {1}, {2}",
result == test.Expected,
result,
test
);
}
}
private static string ReplaceCaseInsensitive(string input, string search, string replacement){
string result = Regex.Replace(
input,
Regex.Escape(search),
replacement.Replace("$","$$"),
RegexOptions.IgnoreCase
);
return result;
}
}
Its output is:
Success: True, Actual: xyzdef, { Input = abcdef, Search = abc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: xyzdef, { Input = ABCdef, Search = abc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: xyzdef, { Input = A*BCdef, Search = a*bc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: x*yzdef, { Input = abcdef, Search = abc, Replacement = x*yz, Expected = x*yzdef}
Success: True, Actual: $def, { Input = abcdef, Search = abc, Replacement = $, Expected = $def }
2.5X FASTER and MOST EFFECTIVE method than other's regular expressions methods:
/// <summary>
/// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another
/// specified string according the type of search to use for the specified string.
/// </summary>
/// <param name="str">The string performing the replace method.</param>
/// <param name="oldValue">The string to be replaced.</param>
/// <param name="newValue">The string replace all occurrences of <paramref name="oldValue"/>.
/// If value is equal to <c>null</c>, than all occurrences of <paramref name="oldValue"/> will be removed from the <paramref name="str"/>.</param>
/// <param name="comparisonType">One of the enumeration values that specifies the rules for the search.</param>
/// <returns>A string that is equivalent to the current string except that all instances of <paramref name="oldValue"/> are replaced with <paramref name="newValue"/>.
/// If <paramref name="oldValue"/> is not found in the current instance, the method returns the current instance unchanged.</returns>
[DebuggerStepThrough]
public static string Replace(this string str,
string oldValue, string newValue,
StringComparison comparisonType)
{
// Check inputs.
if (str == null)
{
// Same as original .NET C# string.Replace behavior.
throw new ArgumentNullException(nameof(str));
}
if (str.Length == 0)
{
// Same as original .NET C# string.Replace behavior.
return str;
}
if (oldValue == null)
{
// Same as original .NET C# string.Replace behavior.
throw new ArgumentNullException(nameof(oldValue));
}
if (oldValue.Length == 0)
{
// Same as original .NET C# string.Replace behavior.
throw new ArgumentException("String cannot be of zero length.");
}
//if (oldValue.Equals(newValue, comparisonType))
//{
//This condition has no sense
//It will prevent method from replacesing: "Example", "ExAmPlE", "EXAMPLE" to "example"
//return str;
//}
// Prepare string builder for storing the processed string.
// Note: StringBuilder has a better performance than String by 30-40%.
StringBuilder resultStringBuilder = new StringBuilder(str.Length);
// Analyze the replacement: replace or remove.
bool isReplacementNullOrEmpty = string.IsNullOrEmpty(newValue);
// Replace all values.
const int valueNotFound = -1;
int foundAt;
int startSearchFromIndex = 0;
while ((foundAt = str.IndexOf(oldValue, startSearchFromIndex, comparisonType)) != valueNotFound)
{
// Append all characters until the found replacement.
int charsUntilReplacment = foundAt - startSearchFromIndex;
bool isNothingToAppend = charsUntilReplacment == 0;
if (!isNothingToAppend)
{
resultStringBuilder.Append(str, startSearchFromIndex, charsUntilReplacment);
}
// Process the replacement.
if (!isReplacementNullOrEmpty)
{
resultStringBuilder.Append(newValue);
}
// Prepare start index for the next search.
// This needed to prevent infinite loop, otherwise method always start search
// from the start of the string. For example: if an oldValue == "EXAMPLE", newValue == "example"
// and comparisonType == "any ignore case" will conquer to replacing:
// "EXAMPLE" to "example" to "example" to "example" … infinite loop.
startSearchFromIndex = foundAt + oldValue.Length;
if (startSearchFromIndex == str.Length)
{
// It is end of the input string: no more space for the next search.
// The input string ends with a value that has already been replaced.
// Therefore, the string builder with the result is complete and no further action is required.
return resultStringBuilder.ToString();
}
}
// Append the last part to the result.
int charsUntilStringEnd = str.Length - startSearchFromIndex;
resultStringBuilder.Append(str, startSearchFromIndex, charsUntilStringEnd);
return resultStringBuilder.ToString();
}
Note: ignore case == StringComparison.OrdinalIgnoreCase as parameter for StringComparison comparisonType. It is the fastest, case-insensitive way to replace all values.
Advantages of this method:
High CPU and MEMORY efficiency;
It is the fastest solution, 2.5 times faster than other's methods
with regular expressions (proof in the end);
Suitable for removing parts from the input string (set newValue to
null), optimized for this;
Same as original .NET C# string.Replace behavior, same exceptions;
Well commented, easy to understand;
Simpler – no regular expressions. Regular expressions are always slower because of their versatility (even compiled);
This method is well tested and there are no hidden flaws like infinite loop in other's solutions, even highly rated:
#AsValeO: Not works with Regex language elements, so it's not
universal method
#Mike Stillion: There is a problem with this code. If the text in new
is a superset of the text in old, this can produce an endless loop.
Benchmark-proof: this solution is 2.59X times faster than regex from #Steve B., code:
// Results:
// 1/2. Regular expression solution: 4486 milliseconds
// 2/2. Current solution: 1727 milliseconds — 2.59X times FASTER! than regex!
// Notes: the test was started 5 times, the result is an average; release build.
const int benchmarkIterations = 1000000;
const string sourceString = "aaaaddsdsdsdsdsd";
const string oldValue = "D";
const string newValue = "Fod";
long totalLenght = 0;
Stopwatch regexStopwatch = Stopwatch.StartNew();
string tempString1;
for (int i = 0; i < benchmarkIterations; i++)
{
tempString1 = sourceString;
tempString1 = ReplaceCaseInsensitive(tempString1, oldValue, newValue);
totalLenght = totalLenght + tempString1.Length;
}
regexStopwatch.Stop();
Stopwatch currentSolutionStopwatch = Stopwatch.StartNew();
string tempString2;
for (int i = 0; i < benchmarkIterations; i++)
{
tempString2 = sourceString;
tempString2 = tempString2.Replace(oldValue, newValue,
StringComparison.OrdinalIgnoreCase);
totalLenght = totalLenght + tempString2.Length;
}
currentSolutionStopwatch.Stop();
Original idea – #Darky711; thanks #MinerR for StringBuilder.
Lots of suggestions using Regex. How about this extension method without it:
public static string Replace(this string str, string old, string #new, StringComparison comparison)
{
#new = #new ?? "";
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old) || old.Equals(#new, comparison))
return str;
int foundAt = 0;
while ((foundAt = str.IndexOf(old, foundAt, comparison)) != -1)
{
str = str.Remove(foundAt, old.Length).Insert(foundAt, #new);
foundAt += #new.Length;
}
return str;
}
Extensions make our lives easier:
static public class StringExtensions
{
static public string ReplaceInsensitive(this string str, string from, string to)
{
str = Regex.Replace(str, from, to, RegexOptions.IgnoreCase);
return str;
}
}
You can use the Microsoft.VisualBasic namespace to find this helper function:
Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)
.Net Core has this method built-in:
Replace(String, String, StringComparison) Doc. Now we can simply write:
"...".Replace("oldValue", "newValue", StringComparison.OrdinalIgnoreCase)
Modified #Darky711's answer to use the passed in comparison type and match the framework replace naming and xml comments as closely as possible.
/// <summary>
/// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
/// </summary>
/// <param name="str">The string performing the replace method.</param>
/// <param name="oldValue">The string to be replaced.</param>
/// <param name="newValue">The string replace all occurrances of oldValue.</param>
/// <param name="comparisonType">Type of the comparison.</param>
/// <returns></returns>
public static string Replace(this string str, string oldValue, string #newValue, StringComparison comparisonType)
{
#newValue = #newValue ?? string.Empty;
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(oldValue) || oldValue.Equals(#newValue, comparisonType))
{
return str;
}
int foundAt;
while ((foundAt = str.IndexOf(oldValue, 0, comparisonType)) != -1)
{
str = str.Remove(foundAt, oldValue.Length).Insert(foundAt, #newValue);
}
return str;
}
(Edited: wasn't aware of the `naked link' problem, sorry about that)
Taken from here:
string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);
Seems you are not the first to complain of the lack of case insensitive string.Replace.
I have wrote extension method:
public static string ReplaceIgnoreCase(this string source, string oldVale, string newVale)
{
if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
return source;
var stringBuilder = new StringBuilder();
string result = source;
int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
while (index >= 0)
{
if (index > 0)
stringBuilder.Append(result.Substring(0, index));
if (newVale.IsNullOrEmpty().IsNot())
stringBuilder.Append(newVale);
stringBuilder.Append(result.Substring(index + oldVale.Length));
result = stringBuilder.ToString();
index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
}
return result;
}
I use two additional extension methods for previous extension method:
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
public static bool IsNot(this bool val)
{
return val == false;
}
Doesn't this work: I cant imaging anything else being much quicker or easier.
public static class ExtensionMethodsString
{
public static string Replace(this String thisString, string oldValue, string newValue, StringComparison stringComparison)
{
string working = thisString;
int index = working.IndexOf(oldValue, stringComparison);
while (index != -1)
{
working = working.Remove(index, oldValue.Length);
working = working.Insert(index, newValue);
index = index + newValue.Length;
index = working.IndexOf(oldValue, index, stringComparison);
}
return working;
}
}
Extending Petrucio's answer with Regex.Escape on the search string, and escaping matched group as suggested in Steve B's answer (and some minor changes to my taste):
public static class StringExtensions
{
public static string ReplaceIgnoreCase(this string str, string from, string to)
{
return Regex.Replace(str, Regex.Escape(from), to.Replace("$", "$$"), RegexOptions.IgnoreCase);
}
}
Which will produce the following expected results:
Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // Hi $1 Universe
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // heLLo wOrld
However without performing the escapes you would get the following, which is not an expected behaviour from a String.Replace that is just case-insensitive:
Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // (heLLo) wOrld
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // Hi heLLo Universe
Using #Georgy Batalov solution I had a problem when using the following example
string original = "blah,DC=bleh,DC=blih,DC=bloh,DC=com";
string replaced = original.ReplaceIgnoreCase(",DC=", ".")
Below is how I rewrote his extension
public static string ReplaceIgnoreCase(this string source, string oldVale,
string newVale)
{
if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
return source;
var stringBuilder = new StringBuilder();
string result = source;
int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
bool initialRun = true;
while (index >= 0)
{
string substr = result.Substring(0, index);
substr = substr + newVale;
result = result.Remove(0, index);
result = result.Remove(0, oldVale.Length);
stringBuilder.Append(substr);
index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
}
if (result.Length > 0)
{
stringBuilder.Append(result);
}
return stringBuilder.ToString();
}
My this Method could Ignore Case as well as Select Only Whole Word
public static string Replace(this string s, string word, string by, StringComparison stringComparison, bool WholeWord)
{
s = s + " ";
int wordSt;
StringBuilder sb = new StringBuilder();
while (s.IndexOf(word, stringComparison) > -1)
{
wordSt = s.IndexOf(word, stringComparison);
if (!WholeWord || ((wordSt == 0 || !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt - 1, 1)))) && !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt + word.Length, 1)))))
{
sb.Append(s.Substring(0, wordSt) + by);
}
else
{
sb.Append(s.Substring(0, wordSt + word.Length));
}
s = s.Substring(wordSt + word.Length);
}
sb.Append(s);
return sb.ToString().Substring(0, sb.Length - 1);
}
Another way is to ignore the case sensitivity in String.Replace() using the option StringComparison.CurrentCultureIgnoreCase
string.Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase)
I recommend the StringComparison.CurrentCultureIgnoreCase method as proposed by ZZY / Gama Sharma. This is just another technique that could be used with LINQ:
List<string> ItemsToRedact = new List<string> { "star", "citizen", "test", "universe"};
string Message = "Just like each sTaR is unique yet mAkes the uniVERSE what it is, the light in you makes you who you are";
List<string> ReplacementList = Message.Split(' ').Where(x => ItemsToRedact.Contains(x.ToLower())).ToList();
foreach (var word in ReplacementList)
{
Message = Message.Replace(word, "[Redacted] ");
}
Console.WriteLine(Message);
returns: Just like each [Redacted] is unique yet mAkes the [Redacted] what it is, the light in you makes you who you are
This code could be further distilled but I broke it up for readability
Below function is to remove all match word like (this) from the string set. By Ravikant Sonare.
private static void myfun()
{
string mystring = "thiTHISThiss This THIS THis tThishiThiss. Box";
var regex = new Regex("this", RegexOptions.IgnoreCase);
mystring = regex.Replace(mystring, "");
string[] str = mystring.Split(' ');
for (int i = 0; i < str.Length; i++)
{
if (regex.IsMatch(str[i].ToString()))
{
mystring = mystring.Replace(str[i].ToString(), string.Empty);
}
}
Console.WriteLine(mystring);
}
You can also try the Regex class.
var regex = new Regex( "camel", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "horse" );
Use this, Tested and 100% Worked!
For VB.NET
Dim myString As String
Dim oldValue As String
Dim newValue As String
myString = Form1.TextBox1.Text
oldValue = TextBox1.Text
newValue = TextBox2.Text
Dim working As String = myString
Dim index As Integer = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase)
While index <> -1
working = working.Remove(index, oldValue.Length)
working = working.Insert(index, newValue)
index = index + newValue.Length
index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase)
Form1.TextBox1.Text = working
End While
For C#
private void Button2_Click(System.Object sender, System.EventArgs e)
{
string myString;
string oldValue;
string newValue;
myString = Form1.TextBox1.Text;
oldValue = TextBox1.Text;
newValue = TextBox2.Text;
string working = myString;
int index = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase);
while (index != -1)
{
working = working.Remove(index, oldValue.Length);
working = working.Insert(index, newValue);
index = index + newValue.Length;
index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase);
Form1.TextBox1.Text = working;
}
}
I prefer this - "Hello World".ToLower().Replace( "world", "csharp" );

Categories

Resources