C# - Split a string with spaces in between in multiple strings [duplicate] - c#

This question already has answers here:
Best way to specify whitespace in a String.Split operation
(11 answers)
C# Splitting Strings on `#` character
(3 answers)
Closed 7 years ago.
I have a string which is a sentence. For example:
string sentence = "Example sentence";
How can I divide this string into multiple strings? So:
string one = "Example";
string two = "sentence";

This is a dupe but you are looking for string.Split (https://msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspx) --
public class Program
{
public static void Main(string[] args)
{
string sentence = "Example sentence";
string[] array = sentence.Split(' ');
foreach (string val in array.Where(i => !string.IsNullOrEmpty(i)))
{
Console.WriteLine(val);
}
}
}
The .Where ensures empty strings are skipped.

This will work
string sentence = "Example sentence";
string [] sentenses = sentence.Split(' ');
string one = sentenses[0];
string two = sentenses[1];

Related

Cannot convert string to IEnumerable<string> [duplicate]

This question already has answers here:
split a string on newlines in .NET
(17 answers)
Closed 1 year ago.
I need to convert string to IEnumerable<string> by every newline character.
I just want the same functionality as File.ReadLines without loading any file, rather taking it from a previously loaded string.
String.Split can split your string and give you string[]
Usage
string someString = ...;
string[] lines = someString.Split('\n');
IEnumerable<string> linesAsEnumerable = lines;
DoSomethingWithLines(linesAsEnumerable);
You could split it according to the newline character:
String[] lines = fileContenets.Split('\n');

Split a file using specific word in C# [duplicate]

This question already has answers here:
How to tell a RegEx to be greedy on an 'Or' Expression
(2 answers)
Closed 2 years ago.
there is a file which i want to split
MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M
MSH|^~\&||||^qweqwewqe|||qwewqeqw|637226866166648574|637226866166648574|2.4
EVN|P03|20200416|20200416
PID|1|PW907441|PW907441|PW907441|Purvis^Walter^Rayshawn||19700524|M
I want to split it using MSH so that the result would be an array of string
array[0]=
"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
array[1]=
"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
What I have tried so far:
string[] sentences = Regex.Split(a, #"\W*((?i)MSH(?-i))\W*");
result:
array[0]="";
array[1]="MSH";
array[2]="asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
array[3]="MSH";
array[4]="asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
Or atleast it should not miss |^~\&||||^ after split in index 1 and 2
You can simply use the Split() function for this. Below generates an IEnumerable, which you can make an array using ToArray if you wanted to:
void Main()
{
string s = #"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M
MSH|^~\&||||^qweqwewqe|||qwewqeqw|637226866166648574|637226866166648574|2.4
EVN|P03|20200416|20200416
PID|1|PW907441|PW907441|PW907441|Purvis^Walter^Rayshawn||19700524|M";
foreach (var element in s.Split(new string[] { "MSH" }, StringSplitOptions.RemoveEmptyEntries).Select(x => $"MSH{x}"))
{
Console.WriteLine(element);
}
}
If you want to split on MSH, Cetin Basoz is right. It will perfectly work doing that :
var sentences = a.Split(new String[] { "MSH" }, StringSplitOptions.RemoveEmptyEntries);
If you wanna be case insensitive, you can use that which is much simpler than the regex you used previously :
var sentences = Regex.Split(a, "MSH", RegexOptions.IgnoreCase);

Substring in c# to find second part in the string [duplicate]

This question already has answers here:
How can I split a string with a string delimiter? [duplicate]
(7 answers)
Closed 4 years ago.
How to find the second part of the string using substring in c#
I have follwwing string:
string str = "George Micahel R - 412352434";
I wanted the above string as two parts.Before "-" and after "-"
I have my first part using following code:
string firstPart = str.Substring(0,str.IndexOf(" - "));
When I am trying for the second part using the following code it gives me an error.
string secondPart = str.Substring(str.IndexOf(" - "), Len(str);
How to get the second part(only number)?
Thanks in advance.
Simply use split function:
var splittedArray = str.Split('-');
var leftPart = splittedArray[0];
var rightPart = splittedArray[1];
Use the Split() method instead.
string str = "George Micahel R - 412352434";
string[] words = str.Split('-');
Console.WriteLine(words[0].Trim()); # George Micahel R
Console.WriteLine(words[1].Trim()); # 412352434

How would I remove a letter from a string if it is found with .Contains? [duplicate]

This question already has answers here:
Remove characters from C# string
(22 answers)
Closed 5 years ago.
I would like to be able to:
Check each character in a string (userInput)
If second string contains this character, remove it from the string
Therefore:
Take every character in a string and validate that these characters are all in the second string.
For example, if the second string was: "abcdefg" and the user input was "acf", the code should remove the characters "a" "c" and "f" from "abcdefg", therefore checking that all input values are valid (in the other string). This way, duplicates are accounted for.
The code I have currently:
foreach (char letter in userInput)
{
if (letters.Contains(letter))
{
//Here would be the code for removing the character from the string
Console.ReadKey();
}
else
{
Console.WriteLine("Cheater!");
Console.ReadKey();
Environment.Exit(0);
}
}
string letters = contains 7 letters
string userInput = used to input letters up to 7.
string str = "abcdef";
string rem = "acf";
foreach (char cc in rem)
{
str = str.Replace(cc.ToString(), "");
}
Console.WriteLine(str);

Split a string after reading square brackets in c# [duplicate]

This question already has answers here:
splitting a string based on multiple char delimiters
(7 answers)
Closed 5 years ago.
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string new = test.Trim("[");
I want output "AccoutNumber".
I have tried the below code but not getting the desired result:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[');
string newvalue = test[1];
Just use Split with two delimiters:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[', ']');
string newvalue = test[1];
You can also use Regex:
string test = "Account.Parameters[\"AccountNumber\"].Caption";
var match = System.Text.RegularExpressions.Regex.Match(test, ".*?\\.Parameters\\[\"(.*?)\"]");
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
.*? is a non greedy wildcart capture, so it will match your string until it reaches the next part (in our case, it will stop at .Parameters[", match the string, and then at "])
It will match .Parameters["..."]., and extract the "..." part.
you can do a Split to that string...
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string output = test.Split('[', ']')[1];
Console.WriteLine(output);

Categories