I have a string which look likes
E-1,E-2,F-3,F-1,G-1,E-2,F-5
Now i want output in array like
E, F, G
I only want the name of character once that appears in the string.
My Code Sample is as follows
string str1 = "E-1,E-2,F-3,F-1,G-1,E-2,F-5";
string[] newtmpSTR = str1.Split(new char[] { ',' });
Dictionary<string, string> tmpDict = new Dictionary<string, string>();
foreach(string str in newtmpSTR){
string[] tmpCharPart = str.Split('-');
if(!tmpDict.ContainsKey(tmpCharPart[0])){
tmpDict.Add(tmpCharPart[0], "");
}
}
Is there any easy way to do it in c#, using string function, If yes the how
string input = "E-1,E-2,F-3,F-1,G-1,E-2,F-5";
string[] splitted = input.Split(new char[] { ',' });
var letters = splitted.Select(s => s.Substring(0, 1)).Distinct().ToList();
Maybe you can obtain the same result with a regular expression! :-)
Related
How can i add a symbol between the array of strings in this method? I tried using an if statement within the for each loop that added the symbol between each index of the array but it didn't work.
public string addSymbolBetweenStringArray(string[] strArray, string symbol)
{
string s = default(string);
foreach (string str in strArray)
{
}
return s;
}
string[] strArray = { "Hello", "World", };
string symbol = "-";
addSymbolBetweenStringArray(stringArray, symbol);
The method then returns Hello-World
You are looking for the string.Join method. For example:
string[] strArray = { "Hello", "World", };
string symbol = "-";
var output = string.Join(symbol, strArray);
You can use String.Join:
string result = String.Join(symbol, strArray);
Split string by List:
I have SplitColl with delimeters:
xx
yy
..
..
And string like this:
strxx
When i try to split string:
var formattedText = "strxx";
var lst = new List<String>();
lst.Add("xx");
lst.Add("yy");
var arr = formattedText.Split(lst.ToArray(), 10, StringSplitOptions.RemoveEmptyEntries);
I have "str" result;
But how to skip this result? I want to get empty array in this case (when delim is a part of a word).
I expect, that when formattedText="str xx", result is str.
EDIT:
I have a many delimeters of address: such as street,city,town,etc.
And i try to get strings like: city DC-> DC.
But, when i get a word like:cityacdc-> i get acdc, but it not a name of a city.
It seems that you are not using your keywords really as delimiters but as search criterion. In this case you could use RegEx to search for each pattern. Here is an example program to illustrate this procedure:
static void Main(string[] args)
{
List<string> delim = new List<string> { "city", "street" };
string formattedText = "strxx street BakerStreet cityxx city London";
List<string> results = new List<string>();
foreach (var del in delim)
{
string s = Regex.Match(formattedText, del + #"\s\w+\b").Value;
if (!String.IsNullOrWhiteSpace(s))
{
results.Add(s.Split(' ')[1]);
}
}
Console.WriteLine(String.Join("\n", results));
Console.ReadKey();
}
This would handle this case:
And I try to get strings like: city DC --> DC
to handle the case where you want to find the word in front of your keyword:
I expect, that when formattedText="str xx", result is str
just switch the places of the matching criterion:
string s = Regex.Match(formattedText, #"\b\w+\s"+ del).Value;
and take the first element at the split
results.Add(s.Split(' ')[0]);
Give this a try, basically what I'm doing is first I remove any leading or tailing delimiters (only if they are separated with a space) from the formattedText string. Then using the remaining string I split it for each delimiter if it has spaces on both sides.
//usage
var result = FormatText(formattedText, delimiterlst);
//code
static string[] FormatText(string input, List<string> delimiters)
{
delimiters.ForEach(d => {
TrimInput(ref input, "start", d.ToCharArray());
TrimInput(ref input, "end", d.ToCharArray());
});
return input.Split(delimiters.Select(d => $" {d} ").ToArray(), 10, StringSplitOptions.RemoveEmptyEntries);
}
static void TrimInput(ref string input, string pos, char[] delimiter)
{
//backup
string temp = input;
//trim
input = (pos == "start") ? input.TrimStart(delimiter) : input.TrimEnd(delimiter);
string trimmed = (pos == "start") ? input.TrimStart() : input.TrimEnd();
//update string
input = (input != trimmed) ? trimmed : temp;
}
How can I use Regular Expressions to split this string
String s = "[TEST name1=\"smith ben\" name2=\"Test\" abcd=\"Test=\" mmmm=\"Test=\"]";
into a list like below:
name1 smith ben
name2 Test
abcd Test=
mmmm Test=`
It is similar to getting attributes from an element but not quite.
The first thing to do is remove the brackets and 'TEST' part from the string so you are just left with the keys and values. Then you can split it (based on '\"') into an array, where the odd entries will be the keys, and the even entries will be the values. After that, it's easy enough to populate your list:
String s = "[TEST name1=\"smith ben\" name2=\"Test\" abcd=\"Test=\" mmmm=\"Test=\"]";
SortedList<string, string> list = new SortedList<string, string>();
//Remove the start and end tags
s = s.Remove(0, s.IndexOf(' '));
s = s.Remove(s.LastIndexOf('\"') + 1);
//Split the string
string[] pairs = s.Split(new char[] { '\"' }, StringSplitOptions.None);
//Add each pair to the list
for (int i = 0; i+1 < pairs.Length; i += 2)
{
string left = pairs[i].TrimEnd('=', ' ');
string right = pairs[i+1].Trim('\"');
list.Add(left, right);
}
Suppose i have a string separator eg "~#" and have a string like "leftSide~#righside"
How do you get you leftside and rightside without separator?
string myLeft=?;
string myRight=?
How do you do it?
thanks
string[] splitResults = myString.Split(new [] {"~#"}, StringSplitOptions.None);
And if you want to make sure you get at most 2 substrings (left and right), use:
int maxResults = 2;
string[] splitResults =
myString.Split(new [] {"~#"}, maxResults, StringSplitOptions.None)
string[] strs =
string.Split(new string[] { "~#" }, StringSplitOptions.RemoveEmptyEntries);
use String.Split
string str = "leftSide~#righside";
str.Split(new [] {"~#"}, StringSplitOptions.None);
the split function has an overload that accepts an array of strings instead of chars...
string s = "leftSide~#righside";
string[] ss = s.Split(new string[] {"~#"}, StringSplitOptions.None);
var s = "leftSide~#righside";
var split = s.Split (new string [] { "~#" }, StringSplitOptions.None);
var myLeft = split [0];
var myRight = split [1];
String myLeft = value.Substring(0, value.IndexOf(seperator));
String myRight = value.Substring(value.IndexOf(seperator) + 1);
What if I want to split a string using a delimiter that is a word?
For example, This is a sentence.
I want to split on is and get This and a sentence.
In Java, I can send in a string as a delimiter, but how do I accomplish this in C#?
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
Example from the docs:
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ...
result = source.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
You can use the Regex.Split method, something like this:
Regex regex = new Regex(#"\bis\b");
string[] substrings = regex.Split("This is a sentence");
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
Edit: This satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.
Based on existing responses on this post, this simplify the implementation :)
namespace System
{
public static class BaseTypesExtensions
{
/// <summary>
/// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
/// </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string[] Split(this string s, string separator)
{
return s.Split(new string[] { separator }, StringSplitOptions.None);
}
}
}
string s = "This is a sentence.";
string[] res = s.Split(new string[]{ " is " }, StringSplitOptions.None);
for(int i=0; i<res.length; i++)
Console.Write(res[i]);
EDIT: The "is" is padded on both sides with spaces in the array in order to preserve the fact that you only want the word "is" removed from the sentence and the word "this" to remain intact.
...In short:
string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);
Or use this code; ( same : new String[] )
.Split(new[] { "Test Test" }, StringSplitOptions.None)
You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.
Here is an extension function to do the split with a string separator:
public static string[] Split(this string value, string seperator)
{
return value.Split(new string[] { seperator }, StringSplitOptions.None);
}
Example of usage:
string mystring = "one[split on me]two[split on me]three[split on me]four";
var splitStrings = mystring.Split("[split on me]");
var dict = File.ReadLines("test.txt")
.Where(line => !string.IsNullOrWhitespace(line))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0], parts => parts[1]);
or
enter code here
line="to=xxx#gmail.com=yyy#yahoo.co.in";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);
ans:
tokens[0]=to
token[1]=xxx#gmail.com=yyy#yahoo.co.in
string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));