How do I split a list on a certain character? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 18 hours ago.
Improve this question
For example, if I have this string: this is item 1 (splithere) this is item 2
Then I want to split the list on character (splithere)
So then the array will be:
[ "this is item 1", "this is item 2" ]
Is there a method for this solution?

You can use string.Split()
var myString = "word1 delimiter word2";
var myList = myString.Split("delimiter");
myList will be ["word1 ", " word2"]
See more here: https://learn.microsoft.com/en-us/dotnet/csharp/how-to/parse-strings-using-split

you can use the String.Split method to split a string into an array of substrings based on a specified delimiter. Here's an example:
string input = "this is item 1 (splithere) this is item 2";
string delimiter = "(splithere)";
string[] items = input.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
In this example, we're using the Split method to split the input string into an array of substrings using the (splithere) delimiter. The second parameter, StringSplitOptions.RemoveEmptyEntries, specifies that any empty entries in the resulting array should be removed.
After running this code, the items array will contain the following two strings:
["this is item 1 ", " this is item 2"]

string str = "this is item 1 (splithere) this is item 2"
var arr = str.Split(new[] {"(splithere)"}, StringSplitOptions.None)

Related

Lambda Expression : Pick out a substring from a larger string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
This is the string which iam trying to process
var str =
"$filter=HRRepName ne null and HRRepName ne '' and HRRepName eq 'jessica.l.hessling'&$top=1"
Currently using below code to get the substring - jessica.l.hessling
var repName = odataQuery
.Split(new string[] { "eq" }, StringSplitOptions.RemoveEmptyEntries)[1]
.Split(new char[] { (char)39 })[1]
.Replace("'", "")
.Trim();
But this index might create bug later hence i want to use lambda expression.
What I have tried till now :
var repName2 = odataQuery
.Split(new string[] { "HRRepName" }, StringSplitOptions.RemoveEmptyEntries)
.Select(s.Substring(s.IndexOf("eq",StringComparison.Ordinal)+1));
Well, I think Regex might be very good choice here, try below code:
var str = "$filter=HRRepName ne null and HRRepName ne '' and HRRepName eq 'jessica.l.hessling'&$top=1";
var match = (new Regex(#"HRRepName eq '([^']+)")).Match(str);
var extractedString = match.Success ? match.Groups[1] : null;
Explanation: HRRepName eq '([^']+) will match HRRepName eq ' literally, then it will match everything until ' character with ([^']+), brackets mean, that it will be stored in capture group.
You wrote:
this can be any name , i want the string right after eq but before '&'
To find whether items are in a string, and/or extract substrings from a string according to some pattern, RegEx is usually the way to go.
To fetch the data after the first eq and before the first & after this eq:
const string regexPattern = ".*eq(.*)&";
var match = RegEx.Match(regexPattern);
if (match.Success)
{ // found the pattern, it is in Match.Groups
ProcessMatch(match.Groups[1]); // [0] is complete matching string, [1] is first capture
}
The pattern:
*. start the string with zero or more characters
eq until the first occurrence of eq
(*.) capture zero or more characters
& until the first & after this eq
You can test this using one of the online RegEx pattern testers
The captured item is in Match.Groups. I haven't tested it, but as far as I remember, this is an IList, where element [0] is the complete matching string, 1 is the first captured item. Your debugger will show this to you.

How do I remove an X number of capital letters from a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to remove an X number of capital letters from a string.
For example if I had the strings:
string Line1 = "NICEWEather";
and
string Line2 = "HAPpyhour";
How would I create a function that pulls out the 2 sets of Capital letters?
Try using regular expressions with \p{Lu} for a Unicode capital letter
using System.Text.RegularExpressions;
...
// Let's remove 2 or more consequent capital letters
int X = 2;
// English and Russian
string source = "NICEWEather - ХОРОшая ПОГОда - Keep It (HAPpyhour)";
// ather - шая да - Keep It (pyhour)
string result = Regex.Replace(source, #"\p{Lu}{" + X.ToString() + ",}", "");
Here we use \p{Lu}{2,} pattern: capital letter appeared X (2 in the code above) or more times.
To remove capital letter from string
string str = " NICEWEather";
Regex pattern = new Regex("[^a-z]");
string result = pattern.Replace(str, "");
Console.WriteLine(result );
output: ather
to remove capital letter if occurrences more than once in sequence order then try this
string str = " NICEWEather";
Regex pattern = new Regex(#"\p{Lu}{2,}");
string output = pattern.Replace(str, "");
Console.WriteLine(output);

C# How to replace spaces with new lines [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to replace spaces with new lines. My text file looks like:
1 2 3 4 5 6
but I want to myString look like:
1
2
3
4
Code:
StreamReader myReader = new StreamReader("TextFile1.txt");
string myString = myReader.ReadLine();
myString = myString.Replace(' ', '\n');
at current state it is only adding \n over spaces.
Use:
myString = String.Join(Environment.NewLine,
myString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
This will split the string based on space and then join them using Environment.NewLine. So in case of multiple spaces only one new line will appear.
You can use Environment.NewLine:
myString = myString.Replace(' ', Environment.NewLine);
This is a platform-independent line-replace. Don't use '\n'.
Environment.NewLine basically outputs "\r\n" for non-Unix platforms, and "\n" for Unix platforms. You are not on a Unix platform, so it is not outputting correctly.
You will run into a lot of weird problems if you use \n, and/or \r\n\ in the future. It's best to just use Environment.NewLine. This works on MessageBox.Show() dialogs, in StreamWriter, StreamReader, etc.
You can port the code anywhere, whereas if you were to use \n or \r\n, you'd be restricted to the platform which supports it.
Use regular expressions to replace each spaces with new lines.
using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
var input = "1 2 3 4 5 6";
Console.WriteLine("input:");
Console.WriteLine(input);
var output = Regex.Replace(input, " ", "\n");
Console.WriteLine("output:");
Console.WriteLine(output);
}
}
https://dotnetfiddle.net/F6vmj4

How can I return the index of the second word in a string that can have multiple white spaces followed by one word followed by multiple white spaces? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
String str =" vol ABCD C XYZ";
I want to return the index of "A"
Note: There are multiple white spaces before all words including the first.
This will get the index of A in your original example (String str =" vol ABCD C XYZ";):
int indexOfABCD = str.IndexOf(str.Trim()[str.Trim().IndexOf(' ')+1]);
If you have something like String str = " vol ABCD C XYZ"; where there are multiple spaces:
string secondword = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
int indexOfAinABCD = str.IndexOf(secondword.First());
If you want to get the indices of all the letters in the second word:
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
EDIT:
This will fail if you have A anywhere else in the first word. You should get an exact match through Regex:
int indexOfAinABCD = Regex.Match(str, string.Format(#"\W{0}\W",secondword)).Index+1;
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
So something like String str = " vABCDol ABCD C XYZ"; won't be an issue

Get values between string in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a string value like "%2%,%12%,%115%+%55%,..."
Sample inputs "(%2%+%5%)/5"
Step1:
get the vales 2 and 5
Step2:
get values from table column2 and column5
step3:
from that value (Column2+Column5)/5
How to get the values from that string
2,12,115,55
Also
commas, "+" (symbols)
Thanks in Advance.
I referred these links:
Find a string between 2 known values
How do I extract text that lies between parentheses (round brackets)?
You can replace the % and then split on the , and +:
var value = "%2%,%12%,%115%+%55%,";
value = value.Replace("%", "");
var individualValues = value.Split(new[] {',', '+'});
foreach (var val in individualValues)
Console.WriteLine(val);
If I understand you correctly...
var string = "%2%,%12%,%115%+%55%";
var values = string.replace("%", "").replace("+", "").split(',');
Edit: Actually, I think you mean you want to split on "+" so that becomes split(',', '+')
str.Replace("%", "").Replace("+",",").Split(',');
This will do it.
Another regex solution:
foreach (Match m in Regex.Matches(str, #"\d+"))
// m.Value is the values you wanted
Using regular expressions:
using System.Text.RegularExpressions;
Regex re = new Regex("\\d+");
MatchCollection matches = re.Matches("%2%,%12%,%115%+%55%,...");
List<int> lst = new List<int>();
foreach (Match m in matches)
{
lst.Add(Convert.ToInt32(m.Value));
}
It's possible parsing the string with splits and other stuff or through Regex:
[TestMethod]
public void TestGetNumberCommasAndPlusSign()
{
Regex r = new Regex(#"[\d,\+]+");
string result = "";
foreach (Match m in r.Matches("%2%,%12%,%115%+%55%,..."))
result += m.Value;
Assert.AreEqual("2,12,115+55,", result);
}

Categories