Split a special character string using c# - c#

I have a string as below
"/calc 2 3 +"
how to split in such a way that i can get
str1="/calc"
str2= "2 3 +"
is there any method in c# does special character splitting?
Thanks!

If it's just that string and always split like you have it, then you can do this:
var x = #"/calc 2 3 +";
var str1 = x.Substring(0, 5);
var str2 = x.Substring(6);
Otherwise, no, there's not special thing that does it because you don't have a unique delimiter.

Use IndexOf method to find the first occurrence of space character. And then use Substring method to split the string into 2.

string strInput = #"/calc 2 3 +";
var list = strInput.Split(' ').ToList();
str1 = list[0];
str2 = String.Join(" ",list.RemoveAt(0));

I'm surprised that no one provided the most obvious answer - using one of the string.Split overloads that allows you to specify the maximum number of substrings to return:
string input = "/calc 2 3 +";
var result = input.Split(new[] { ' ' }, 2);
Debug.Assert(result.Length == 2 && result[0] == "/calc" && result[1] == "2 3 +");

There are lots of ways to do that. The easiest one is to use index of the first space.
var mystr = #"/calc 2 3 +";
int index= mystr.IndexOf(' ');
var str1 = mystr.Substring(0, index);
var str2 = mystr.Substring(index+1);
Also if there is any pattern in your text, you can also use RegEx

string a = "/calc 2 3 +";
string[] array = a.Split(' ');
str1= array[0];
str2= string.Format("{0} {1} {2}", array[1], array[2], array[3]);

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));

Extracting parts of a string c#

In C# what would be the best way of splitting this sort of string?
%%x%%a,b,c,d
So that I end up with the value between the %% AND another variable containing everything right of the second %%
i.e. var x = "x"; var y = "a,b,c,d"
Where a,b,c.. could be an infinite comma seperated list. I need to extract the list and the value between the two double-percentage signs.
(To combat the infinite part, I thought perhaps seperating the string out to: %%x%% and a,b,c,d. At this point I can just use something like this to get X.
var tag = "%%";
var startTag = tag;
int startIndex = s.IndexOf(startTag) + startTag.Length;
int endIndex = s.IndexOf(tag, startIndex);
return s.Substring(startIndex, endIndex - startIndex);
Would the best approach be to use regex or use lots of indexOf and substring to do the extracting based on te static %% characters?
Given that what you want is "x,a,b,c,d" the Split() function is actually pretty powerful and regex would be overkill for this.
Here's an example:
string test = "%%x%%a,b,c,d";
string[] result = test.Split(new char[] { '%', ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result) {
Console.WriteLine(s);
}
Basicly we ask it to split by both '%' and ',' and ignore empty results (eg. the result between "%%"). Here's the result:
x
a
b
c
d
To Extract X:
If %% is always at the start then;
string s = "%%x%%a,b,c,d,h";
s = s.Substring(2,s.LastIndexOf("%%")-2);
//Console.WriteLine(s);
Else;
string s = "v,u,m,n,%%x%%a,b,c,d,h";
s = s.Substring(s.IndexOf("%%")+2,s.LastIndexOf("%%")-s.IndexOf("%%")-2);
//Console.WriteLine(s);
If you need to get them all at once then use this;
string s = "m,n,%%x%%a,b,c,d";
var myList = s.ToArray()
.Where(c=> (c != '%' && c!=','))
.Select(c=>c).ToList();
This'll let you do it all in one go:
string pattern = "^%%(.+?)%%(?:(.+?)(?:,|$))*$";
string input = "%%x%%a,b,c,d";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
// "x"
string first = match.Groups[1].Value;
// { "a", "b", "c", "d" }
string[] repeated = match.Groups[2].Captures.Cast<Capture>()
.Select(c => c.Value).ToArray();
}
You can use the char.IsLetter to get all the list of letter
string test = "%%x%%a,b,c,d";
var l = test.Where(c => char.IsLetter(c)).ToArray();
var output = string.Join(", ", l.OrderBy(c => c));
Since you want the value between the %% and everything after in separate variables and you don't need to parse the CSV, I think a RegEx solution would be your best choice.
var inputString = #"%%x%%a,b,c,d";
var regExPattern = #"^%%(?<x>.+)%%(?<csv>.+)$";
var match = Regex.Match(inputString, regExPattern);
foreach (var item in match.Groups)
{
Console.WriteLine(item);
}
The pattern has 2 named groups called x and csv, so rather than just looping, you can easily reference them by name and assign them to values:
var x = match.Groups["x"];
var y = match.Groups["csv"];

Divide a string at first space

For a chat-bot, if someone says "!say " it will recite what you say after the space. Simple.
Example input:
!say this is a test
Desired output:
this is a test
The string can be represented as s for sake of argument. s.Split(' ') yields an array.
s.Split(' ')[1] is just the first word after the space, any ideas on completely dividing and getting all words after the first space?
I've tried something along the lines of this:
s.Split(' ');
for (int i = 0; i > s.Length; i++)
{
if (s[i] == "!say")
{
s[i] = "";
}
}
The input being:
!say this is a test
The output:
!say
Which is obviously not what I wanted :p
(I know there are several answers to this question, but none written in C# from where I searched.)
Use the overload of s.Split that has a "maximum" parameter.
It's this one:
http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx
Looks like:
var s = "!say this is a test";
var commands = s.Split (' ', 2);
var command = commands[0]; // !say
var text = commands[1]; // this is a test
You can use string.Substring method for that:
s.Substring(s.IndexOf(' '))
var value = "say this is a test";
return value.Substring(value.IndexOf(' ') + 1);
This code is working for me. I added the new [] and it works
var s = "!say this is a test";
var commands = s.Split (new [] {' '}, 2);
var command = commands[0]; // !say
var text = commands[1]; // this is a test

String Search & replacement

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");

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

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;
}**

Categories