String Search & replacement - c#

I have a string "JohnMarkMarkMark"
I want to replace the "Mark" with "Tom" with two cases
In first case i want to replace only first occurance of "Mark" Result will be: "JohnTomMarkMark"
In the second case i want to replace all the occurance of "Mark" Result will be: "JohnTomTomTom"
Please suggest
Thnaks

string data = "JohnMarkMarkMark";
string resultOne = new Regex("Mark").Replace(data, "Tom", 1);
string resultAll = data.Replace("Mark", "Tom");

For the first case, use IndexOf, Substring and Concat.
For the second case, use Replace.

(1) is:
var inString = "TestMarkMarkMark";
var lookFor = "Mark";
var replaceWith = "Tom";
var length = lookFor.Length;
var first = inString.IndexOf(lookFor);
var newString = inString.Substring(0, first) + replaceWith + inString.Substring(first + length);
Which could be optimized, but I've expanded it out so it's easy to follow.
(2) is trivial - just do inString.Replace("Mark", "Tom");

for case 1 try this
string s = "JohnMarkMarkMark";
Regex x = new Regex("Mark");
MatchCollection m = x.Matches(s);
if (m!=null && m.Count > 0)
{
s = s.Remove(m[0].Index, m[0].Length);
s = s.Insert(m[0].Index,"Tom");
}
for case 2 try s = s.Replace("Mark","Tom");

Related

Split a String on 2nd last occurrence of comma in C#

I have a string say
var str = "xy,yz,zx,ab,bc,cd";
and I want to split it on the 2nd last occurrence of a comma in C# i.e
a = "xy,yz,zx,ab"
b = "bc,cd"
How can I achieve this result?
Let's find the required comma index with a help of LastIndexOf:
var str = "xy,yz,zx,ab,bc,cd";
// index of the 2nd last occurrence of ','
int index = str.LastIndexOf(',', str.LastIndexOf(',') - 1);
Then use Substring:
string a = str.Substring(0, index);
string b = str.Substring(index + 1);
Let's have a look:
Console.WriteLine(a);
Comsole.WriteLine(b);
Outcome:
xy,yz,zx,ab
bc,cd
Alternative "readable" approach ;)
const string text = "xy,yz,zx,ab,bc,cd";
var words = text.Split(',');
var firstBatch = Math.Max(words.Length - 2, 0);
var first = string.Join(",", words.Take(firstBatch));
var second = string.Join(",", words.Skip(firstBatch));
first.Should().Be("xy,yz,zx,ab"); // Pass OK
second.Should().Be("bc,cd"); // Pass OK
You could handle this via regex replacement:
var str = "xy,yz,zx,ab,bc,cd";
var a = Regex.Replace(str, #",[^,]+,[^,]+$", "");
var b = Regex.Replace(str, #"^.*,([^,]+,[^,]+)$", "$1");
Console.WriteLine(a);
Console.WriteLine(b);
This prints:
xy,yz,zx,ab
bc,cd
It you get Microsoft's System.Interactive extensions from NuGet then you can do this:
string output = String.Join(",", str.Split(',').TakeLast(2));

how To get specific part of a string in c#

I have a string
string a = "(something is there),xyz,(something there)";
and, I use this
string s = "(something is there),xyz,(something there)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
but I want to use the second part (something there)
how can I do it?
a.Split("(),".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
This will return an array with 3 strings: something is there, xyz, and something there
Not sure what exactly you're doing around this, however this does it in this specific case:
var last = s.Split(',').Last(); // "(something there)"
Or more verbosely for explanation:
var s = "(something is there),xyz,(something there)";
var split = s.Split(','); // [ "(something is there)", "xyz", "(something there)" ]
var last = split.Last(); // "(something there)"
And if you don't want the brackets(en-GB)
var content = last.Trim('(', ')'); // "something there"
If "last" is the same as "second" in this case you can use String.LastIndexOf:
string lastPart = null;
int lastStartIndex = a.LastIndexOf('(');
if (lastStartIndex >= 0)
{
int lastEndIndex = a.LastIndexOf(')');
if (lastEndIndex >= 0)
lastPart = a.Substring(++lastStartIndex, lastEndIndex - lastStartIndex);
}
Here is a solution which extracts all tokens from the string into a List<string>:
int startIndex = -1, endIndex = -1;
var tokens = new List<string>();
while (true)
{
startIndex = a.IndexOf('(', ++endIndex);
if (startIndex == -1) break;
endIndex = a.IndexOf(')', ++startIndex);
if (endIndex == -1) break;
tokens.Add(a.Substring(startIndex, endIndex - startIndex));
}
So now you could use the indexer or Enumerable.ElementAtOrDefault:
string first = tokens[0];
string second = tokens.ElementAtOrDefault(1);
If the list is too small you get null as result. If you just want the last use tokens.Last().
You can use this:
string s = "(something is there),xyz,(something there)";
var start = s.Split(',')[2];
Also You can use:
string s = "(something is there),xyz,(something there)";
Regex regex = new Regex(#"\([^()]*\)(?=[^()]*$)");
Match match = regex.Match("(something is there),xyz,(something there)");
var result = match.Value;
You could use the following if you just want the text:
var s = "(something is there),xyz,(something there)";
var splits = s.Split('(');
var text = splits[2].Trim(')');
If you want to get the text between second '(' and ')' then use the second parameter of IndexOf which sets the starting index for searching
start = s.IndexOf("(", end) + 1;
end = s.IndexOf(")", start);
string secondResult = s.Substring(start, end - start);
If you want to get the string after the last ) use this code:
string otherPart = s.Substring(end+1);

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 to split for only one string without using arrays

I've a string 01-India. I want to split on '-' and get only the code 01. How can I do this. I'm a .net newbie. Split function returns a array. Since I need only one string, how can this be done. Is there a ingenious way to do it using split only. Or do I've to use substring only?
Other possibility is
string xy = "01-India";
string xz = xy.Split('-')[0];
You can search for the first occurence of - and then use the method substring to cut the piece out.
var result = input.Substring(0, input.IndexOf('-'))
string str = "01-India";
string prefix = null;
int pos = str.IndexOf('-');
if (pos != -1)
prefix = str.SubString(0,pos);
var str = "01-India";
var hyphenIndex = str.IndexOf("-");
var start = str.substring(0, hyphenIndex);
or you can use regular expression if it is a more complicated string pattern.
Something like this?
var s = "01-India";
var result = s.SubString(0, s.IndexOf("-"));
Since you don't want to use arrays, you could do an IndexOf('-') and then a substring.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Substring(0, index);
Or, for added fun, you could use String.Remove.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Remove(index);
string value = "01-India";
string part1 = value.Split('-')[0];

Strip prefix and value

if I have the string "freq1" or "freq12" and so on, how can I strip out freq and also the number by itself?
string foo = "freq12";
string fooPart = foo.Substring(4); // "12"
int fooNumber = int.parse(fooPart); // 12
if the "freq" part is not constant, then you can use regular expressions:
using System.Text.RegularExpressions;
string pattern = #"([A-Za-z]+)(\d+)";
string foo = "freq12";
Match match = Regex.Match(foo, pattern);
string fooPart = match.Groups[1].Value;
int fooNumber = int.Parse(match.Groups[2].Value);
Is it always going to be the text freq that prepends the number within the string? If so, your solution is very simple:
var str = "freq12";
var num = int.Parse(str.Substring(4));
Edit: Here's a more generic method in the case that the first part of the string isn't always "freq".
var str = "freq12";
int splitIndex;
for(splitIndex = 0; splitIndex < str.Length; splitIndex++)
{
if (char.IsNumeric(str[splitIndex]))
break;
}
if (splitIndex == str.Length)
throw new InvalidOperationException("The input string does not contain a numeric part.");
var textPart = int.Parse(str.Substring(0, splitIndex));
var numPart = int.Parse(str.Substring(splitIndex));
In the given example, textPart should evaluate to freq and numPart to 12. Let me know if this still isn't what you want.
Try something like this:
String oldString = "freq1";
String newString = oldString.Replace("freq", String.Empty);
If you know that the word "freq" will always be there, then you can do something like:
string number = "freq1".Replace("freq","");
That will result in "1".

Categories