Extract common string from two strings with Comma separated - c#

I have two strings consisting of several words (Comma separated). If string 1 consisting of words (; separated) which is to be ignored if it presents in string 2, below are the strings
var compToIgnore="Samsung,Motorola,Amazon";
var allCompanies="Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
var icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var c in listOfCompanies)
{
if (c.BrandId.StartsWith("A2"))
{
var item = allCompanies.Where(x => !icm.Contains(x));
var result = string.Join(",", item);
}
}
In result variable I wanted to have final result as "Godrej,Videocon,Huawei,Alibaba"
I don't see any proper result with above code

You can try Linq in order to query allCompanies:
using System.Linq;
...
var compToIgnore = "Samsung,Motorola,Amazon";
var allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
string result = string.Join(",", allCompanies
.Split(',')
.Except(compToIgnore.Split(',')));
Note, that Except removes all duplicates. If you want to preserve them, you can use HashSet<string> and Where instead of Except:
HashSet<string> exclude = new HashSet<string>(compToIgnore.Split(','));
string result = string.Join(",", allCompanies
.Split(',')
.Where(item => !exclude.Contains(item)));

Try following :
string compToIgnore = "Samsung,Motorola,Amazon";
string allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
string[] icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] ac = allCompanies.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string results = string.Join(",", ac.Where(x => !icm.Contains(x)));

Related

Prepend/Append string for each element in a string array

I have some code as below:
char[] separator = { ',' };
String[] idList = m_idsFromRequest.Split(separator); //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().ToList();
m_distinctIdList = distinctIdList.ToArray();
m_idsFromRequest = string.Join(" ", distinctIdList);
currently m_idsFromRequest = ["1","2".........."] is as such.
I want to make it ["0|1","0|2".........."] like append "0|" in each element . I wanted to know id I could do it without the foreach loop.
You can use Select and String.Join:
var idsPrependedWithZero = m_idsFromRequest.Split(separator)
.Distinct() // same as in your code
.Select(id => $"0|{id}");
string result = string.Join(",", idsPrependedWithZero);
char[] separator = { ',' };
string m_idsFromRequest = "1,2,3,4,5,6";
String[] idList = m_idsFromRequest.Split(separator); //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().Select(t => "0|" + t).ToList();
m_idsFromRequest = string.Join(",", distinctIdList);
Just added the .Select() after .Distinct(). Inside the .Select you can transform each of the item in the list.
Apart from that i also added "," in your string.Join. Because you want it to be join by comma.

Basic LINQ to Object codes

I'm learing the LINQ.
I made some codes.
string mySource = #"
#16
100%
Monitor
#19
98%
Guide
#77
0%
Cord
";
var myPattern = #"#(\d+)\r\n(\d+)%\r\n([^\r\n]*)\r\n";
var myCollection = Regex.Matches(mySource, myPattern, RegexOptions.Singleline)
.Cast<Match>().ToList();
MessageBox.Show(string.Join("\n", myCollection));
Looks nice.
But, What I really want to do is like this.
(this kind of data structure)
var myList = new List<string[]>();
var myArray1 = new string[] { "#16", "100%", "Monitor" };
var myArray2 = new string[] { "#19", "98%", "Guide" };
var myArray3 = new string[] { "#77", "0%", "Cord" };
myList.Add(myArray1);
myList.Add(myArray2);
myList.Add(myArray3);
What do I have to do ?
Regards
You can do:
List<string[]> myList = myCollection.Select(r => r.Value
.Split(new [] { '\r', '\n'},
StringSplitOptions.RemoveEmptyEntries)
).ToList();
You will end up with a List<T> with three elements, and each element would consists of array of strings.

Check a pattern in a string then convert it to upper case

I was not clear with my previous question
I have a list: new List<string> { "lts", "mts", "cwts", "rotc" };
Now I wan't to check a pattern in string that starts or ends with a forward slash like this: "cTws/Rotc/lTs" or "SomethingcTws cWtS/Rotc rOtc".
and convert to upper case only the string that starts/ends with a forward slash based on the list that I have.
So the output should be: "CWTS/ROTC/LTS", "SomethingcTws CWTS/ROTC rOtc"
I modified Sachin's answer:
List<string> replacementValues = new List<string>
{
"cwts",
"mts",
"rotc",
"lts"
};
string pattern = string.Format(#"\G({0})/?", string.Join("|", replacementValues.Select(x => Regex.Escape(x))));
Regex regExp = new Regex(pattern, RegexOptions.IgnoreCase);
string value = "Cwts/Rotc Somethingcwts1 Cwts/Rotc/lTs";
string result = regExp.Replace(value, s => s.Value.ToUpper());
Result: CWTS/ROTC Somethingcwts1 Cwts/Rotc/lTs
The desired output should be: CWTS/ROTC Somethingcwts1 CWTS/ROTC/LTS
So instead of using Regex, which I'm not really good with, I'm doing split by space then split by "/" then rejoin the strings
string val = "Somethingrotc1 cWts/rOtC/lTs Cwts";
List<string> replacementValues = new List<string>
{
"lts", "mts",
"cwts", "rotc"
};
string[] tokens = val.Split(new char[] { ' ' }, StringSplitOptions.None);
string result = string.Join(" ", tokens.Select(t =>
{
// Now split by "/"
string[] ts = t.Split(new char[] { '/' }, StringSplitOptions.None);
if (ts.Length > 1)
{
t = string.Join("/", ts.Select(x => replacementValues.Contains(x.ToLower()) ? x.ToUpper() : x));
}
return t;
}));
Output: Somethingrotc1 CWTS/ROTC/LTS Cwts
You want to change the specific words in the string to Upper case. Then you can use Regex to achieve it.
string value = "Somethingg1 Cwts/Rotc/Lts Cwts";
var replacementValues = new Dictionary<string, string>()
{
{"Cwts","CWTS"},
{"Rotc","ROTC"},
{"Lts","LTC"}
};
var regExpression = new Regex(String.Join("|", replacementValues.Keys.Select(x => Regex.Escape(x))));
var outputString = regExpression.Replace(value, s => replacementValues[s.Value]);

How to remove " [ ] \ from string

I have a string
"[\"1,1\",\"2,2\"]"
and I want to turn this string onto this
1,1,2,2
I am using Replace function for that like
obj.str.Replace("[","").Replace("]","").Replace("\\","");
But it does not return the expected result.
Please help.
You haven't removed the double quotes. Use the following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");
Here is an optimized approach in case the string or the list of exclude-characters is long:
public static class StringExtensions
{
public static String RemoveAll(this string input, params Char[] charactersToRemove)
{
if(string.IsNullOrEmpty(input) || (charactersToRemove==null || charactersToRemove.Length==0))
return input;
var exclude = new HashSet<Char>(charactersToRemove); // removes duplicates and has constant lookup time
var sb = new StringBuilder(input.Length);
foreach (Char c in input)
{
if (!exclude.Contains(c))
sb.Append(c);
}
return sb.ToString();
}
}
Use it in this way:
str = str.RemoveAll('"', '[', ']', '\\');
// or use a string as "remove-array":
string removeChars = "\"{[]\\";
str = str.RemoveAll(removeChars.ToCharArray());
You should do following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\"","");
string.Replace method does not replace string content in place. This means that if you have
string test = "12345" and do
test.Replace("2", "1");
test string will still be "12345". Replace doesn't change string itself, but creates new string with replaced content. So you need to assign this new string to a new or same variable
changedTest = test.Replace("2", "1");
Now, changedTest will containt "11345".
Another note on your code is that you don't actually have \ character in your string. It's only displayed in order to escape quote character. If you want to know more about this, please read MSDN article on string literals.
how about
var exclusions = new HashSet<char>(new[] { '"', '[', ']', '\\' });
return new string(obj.str.Where(c => !exclusions.Contains(c)).ToArray());
To do it all in one sweep.
As Tim Schmelter writes, if you wanted to do it often, especially with large exclusion sets over long strings, you could make an extension like this.
public static string Strip(
this string source,
params char[] exclusions)
{
if (!exclusions.Any())
{
return source;
}
var mask = new HashSet<char>(exclusions);
var result = new StringBuilder(source.Length);
foreach (var c in source.Where(c => !mask.Contains(c)))
{
result.Append(c);
}
return result.ToString();
}
so you could do,
var result = "[\"1,1\",\"2,2\"]".Strip('"', '[', ']', '\\');
Capture the numbers only with this regular expression [0-9]+ and then concatenate the matches:
var input = "[\"1,1\",\"2,2\"]";
var regex = new Regex("[0-9]+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value);
var result = string.Join(",", matches);

Filtering comma separated String in C#

I have a dynamic String value which may contain values like this
"Apple ,Banana, , , , Mango ,Strawberry , "
I would like to filter this string like
"Apple,Banana,Mango,Strawberry".
I have tried with the following code and it works.
Is there any better approach to achieve the same in C#(.NET 2.0)?
/// <summary>
/// Convert "Comma Separated String" to "Comma Separated String"
/// </summary>
/// <param name="strWithComma">String having values separated by comma</param>
/// <returns>String separated with comma</returns>
private String CommaSeparatedString(String strWithComma)
{
String rtn = String.Empty;
List<String> newList= new List<string>();
if (String.IsNullOrEmpty(strWithComma))
{
return rtn;
}
String[] strArray = strWithComma.Split(",".ToCharArray());
if (strArray == null || strArray.Length == 0)
{
return rtn;
}
String tmpStr = String.Empty;
String separator=String.Empty;
foreach (String s in strArray)
{
if (!String.IsNullOrEmpty(s))
{
tmpStr =s.Replace(Environment.NewLine, String.Empty);
tmpStr = tmpStr.Trim();
if (!String.IsNullOrEmpty(tmpStr))
{
newList.Add(tmpStr);
}
}
}
if (newList != null && newList.Count > 0)
{
rtn = String.Join(",", newList.ToArray());
}
return rtn;
}
you can also use Regex:
string str = #"Apple ,,Banana, , , , Mango ,Strawberry , ";
string result = Regex.Replace(str, #"(\s*,\s*)+", ",").TrimEnd(',');
I believe the following should do the trick on any .NET version:
string[] TrimAll( string[] input )
{
var result = new List<string>();
foreach( var s in input )
result.Add( s.Trim() );
}
return result.ToArray();
}
var delimiters = new [] { ",", "\t", Environment.NewLine };
string result = string.Join(",", TrimAll( input.Split( delimiters, StringSplitOptions.RemoveEmptyEntries ) ) );
Edit: updated to deal with white-space, tabs and newline.
Assuming that your items do not contain spaces:
private String CommaSeparatedString(String strWithComma)
{
string[] tokens = strWithComma
.Replace(" ", "")
.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
return string.Join(",", tokens);
}
Now I'm not sure if C# 2.0 accepts the new char[] {','} syntax. If not, you can define the array somewhere else (as a class private member, for example).
Here's a one-liner:
var outputString = string.Join(",", inputString.Replace(" ", string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
Regex regex = new Regex(#"\w(?:(?!,| ).)*");
var items = regex.Matches("Apple ,Banana, , , , Mango ,Strawberry , ").Cast<Match>().Select(m => m.Value);
.NET 2.0 Version
List<string> newList = new List<string>();
Regex regex = new Regex(#"\w(?:(?!,| ).)*");
string str = "Apple ,Banana, , , , Mango ,Strawberry , ";
MatchCollection matches = regex.Matches(str);
foreach (Match match in matches)
{
newList.Add(match.Value);
}
var result = Regex.Replace(strWithComma, ",+", ",").TimEnd(',');
result = Regex.Replace(result, "\s+", string.Empty);
With no regular expressions, no splits and joins, trims, etc, O(n) time. StringBuilder is a very good class to work with strings.
EDIT
If the string it doesn't end with a letter it will add a comma. So an extra TrimEnd(',') is added
string strWithComma = ",Apple ,Banana, , , , Mango ,Strawberry , \n John,";
var sb = new StringBuilder();
var addComma = false;
foreach (var c in strWithComma )
{
if (Char.IsLetter(c)) // you might want to allow the dash also: example Anne-Marie
{
addComma = true;
sb.Append(c);
}
else
{
if (addComma)
{
addComma = false;
sb.Append(',');
}
}
}
string rtn = sb.ToString().TrimEnd(',');
Warning this method will only apply for C# 3.0 or higher. Sorry guys didnt read the question well enough
This will work but it can be done much easier like:
string input = "apple,banana,, \n,test\n, ,juice";
var parts = from part in input.Split(',')
let trimmedPart = part.Replace("\n", "")
where !string.IsNullOrWhiteSpace(trimmedPart)
select trimmedPart;
string result = string.Join(",", parts);

Categories

Resources