Merge 2 Numeric strings Alternatively every Nth place [closed] - c#

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 11 months ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have 2 Numeric strings with commas:
8,1,6,3,16,9,14,11,24,17,22,19
and
2,7,4,5,10,15,12,13,18,23,20,21
and I need to merge them Alternatively every Nth place
(for Example every 4th place to get)
8,1,2,7,6,3,4,5,16,9,10,15,14,11,12,13,24,17,18,23,22,19,20,21
I've already examined all recommended solutions but nothing worked for me.
Here's my current progress:
string result = "";
// For every index in the strings
for (int i = 0; i < JoinedWithComma1.Length || i < JoinedWithComma2.Length; i=i+2)
{
// First choose the ith character of the
// first string if it exists
if (i < JoinedWithComma1.Length)
result += JoinedWithComma1[i];
// Then choose the ith character of the
// second string if it exists
if (i < JoinedWithComma2.Length)
result += JoinedWithComma2[i];
}
Appreciate any assistance.

You can't rely on the length of the strings or select the "ith character" because not all "elements" (read: numbers) have the same number of characters. You should split the strings so you can get the elements out of the result arrays instead:
string JoinedWithComma1 = "8,1,6,3,16,9,14,11,24,17,22,19";
string JoinedWithComma2 = "2,7,4,5,10,15,12,13,18,23,20,21";
var split1 = JoinedWithComma1.Split(',');
var split2 = JoinedWithComma2.Split(',');
if (split1.Length != split2.Length)
{
// TODO: decide what you want to happen when the two strings
// have a different number of "elements".
throw new Exception("Oops!");
}
Then, you can easily write a for loop to merge the two lists:
var merged = new List<string>();
for (int i = 0; i < split1.Length; i += 2)
{
if (i + 1 < split1.Length)
{
merged.AddRange(new[] { split1[i], split1[i + 1],
split2[i], split2[i + 1] });
}
else
{
merged.AddRange(new[] { split1[i], split2[i] });
}
}
string result = string.Join(",", merged);
Console.WriteLine(
result); // 8,1,2,7,6,3,4,5,16,9,10,15,14,11,12,13,24,17,18,23,22,19,20,21
Try it online.

If you write a regular expression to get you a pair of numbers:
var r = new Regex(#"\d+,\d+");
You can break each string into a sequence of pairs:
var s1pairs = r.Matches(s1).Cast<Match>().Select(m => m.ToString());
var s2pairs = r.Matches(s2).Cast<Match>().Select(m => m.ToString());
And you can zip the sequences
var zipped = s1pairs.Zip(s2pairs,(a,b)=>a+","+b);
And join the bits together with commas
var result = string.Join(",", zipped);
How does it work?
The Regex matches any number of digits, followed by a comma, followed by any number of digits
In a string of
1,2,3,4,5,6
It matches 3 times:
1,2
3,4
5,6
Matches returns a MatchCollection containing all these matches. To be compatible with LINQ Select you need to Cast the MatchCollection to an IEnumerable<Match>. It is this way because MatchCollection predates the invention of IEnumerable<T> so it's enumerator returns objects that need casting. Once turned into an IEnumerable<Match> each match can be ToString'd by a Select, producing a sequence of strings that are pairs of numbers separated by comma. An s1pairs is effectively a collection of pairs of numbers:
new []{ "1,2", "3,4", "5,6" }
Repeat the same for string 2
Zip the sequences. As you might imagine from the name, Zip takes one from A then one from B then one from A then one from B, merging them like a zipper on clothing so two sequences of
new [] { "1,2", "3,4" }
new [] { "A,B", "C,D" }
When zipped end up as
new [] { "1,2,A,B", "3,4,C,D" }
And all that remains is to join it back together with a comma
"1,2,A,B,3,4,C,D"

Related

c# find keywords in a string and remove it [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 3 years ago.
Improve this question
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method:
private string RemoveFromList(string sentence)
{
var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" };
var control = lists.Any(sentence.Contains);
string result;
if (control)
{
var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains)
?? throw new InvalidOperationException(), StringComparison.Ordinal);
result = index != -1 ? sentence.Remove(index) : sentence;
}
else
result = sentence;
return result;
}
var str = "ask- This is a sentence.";
Message.Box(RemoveFromList(str));
// It does not give to me: This is a sentence.
This method does not work properly. It does not remove the keyword from the string.
Using string.Replace is the simplest approach:
foreach (var word in lists)
{
sentence = sentence.Replace(word,"").Trim();
}
Although that will find the word in the middle of the string too. If you wanted to remove it only at the start you could use IndexOf check it's 0 and then take the string starting from word.Length using Substring. Or use StartsWith:
foreach (var word in lists)
{
if (sentence.StartsWith(word))
{
sentence = sentence.Substring(word.Length).Trim();
// break; // if only one
}
}
There are 2 options for you.
First of all the Remove usage is incorrect. You just want to remove the keyword. If u pass 1 argument to remove it will remove from that index till end. Pass the length of keyword as second arg to Remove.
s.Remove(index, len);
If string contains it than replace the occurrence of keyword with empty string
s.Replace("keyword", "");
Another option is you could create an extension since you already know what items to remove.
using System.Text.RegularExpressions;
public static string RemoveFromList(this string sentence)
{
new List<string>{ "ask-",
"que-",
"(app)",
"(exe)",
"(foo)" }.ForEach(name =>
{
sentence = Regex.Replace(sentence.Replace(name, string.Empty), " {2,}", " ");
});
return sentence;
}
Useage
var str = "ask- This is (app) a que- sentence.".RemoveFromList();
Note
I used Regex.Replace as it's possible you may have some blank spaces floating around after you remove the bad string/s, this helps ensure that doesn't happen.

Splitting C# string into 3 word chunks using regex or other method [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 5 years ago.
Improve this question
I would like to make a feature where a string in C# can be broken into 3 word chunks like this:
Today is a nice day, and I have been driving a car /*(don't laugh lol - not a part of sentence)*/
So the first thing that I would like to do is throw out all special characters from string except for numbers and letters.
And once I do that, then goes the breaking the word into a 3 word chunk, where the output in the case of upper sentence would be:
Today is a
nice day and
I have been
driving a car
I was thinking to do this via regex, but then again there's LINQ methods and all that could solve this easily, so I'm not really sure which way to choose to choose in order to make this? What would be the most efficient way?
P.S. Also a problem that I'm thinking of is what if a word has 8 words and I want to make it into 3 chunk words...? How would I then throw out the last 2 words that don't match the criteria of forming the 3 chunk "sentence"?
Can someone help me out ?
string str = "Today is a nice day, and I have been driving a car";
str = Regex.Replace(str, "[^0-9a-zA-Z ]+", "");
string[] arr = str.Split(' ');
int nElements = 0;
for (int i = 0; i < arr.Length; i+=3)
{
if(i+3 < arr.Length)
{
nElements = 3;
}
else
{
nElements = arr.Length - i;
}
Console.WriteLine(arr.Skip(i).Take(nElements).Aggregate((current, next) => current + " " + next));
}
Get all words by using regex ([a-zA-Z]+), then put it into array and from that build 3 words chunk into a array or list.
If you have 8 words you can check if array can be divided by 3 if not just delete last two or one word. Code look like this:
string str = "Today is a nice day, and I have been driving a car";
Regex r = new Regex("[a-zA-Z]+", RegexOptions.IgnoreCase);
var wordCollection = r.Matches(str).Cast<Match>().Select(m => m.Value).ToList();
var number = wordCollection.Count % 3;
if (number == 1)
{
wordCollection.RemoveAt(wordCollection.Count - 1);
}
else if (number == 2)
{
wordCollection.RemoveAt(wordCollection.Count - 1);
wordCollection.RemoveAt(wordCollection.Count - number - 1);
}
var list = new List<string>();
for (var i = 0; i < wordCollection.Count; i+=3)
{
list.Add(string.Format("{0} {1} {2}", wordCollection[i], wordCollection[i + 1], wordCollection[i + 2]));
}
Edit:
Add howManyToRemove variable to check if i need to delete one or two words.
Edit 2:
There was a little bug in my code, I fix it.
I think here is one of the primitive ways to do that:
You should split your input string by " " which is done by using string.Split() function, which splits by white space if no argument was passed.
Now you should just pass the array you have got from split and take by 3 element.
For removing special symbols from element you can use the following RegEx pattern [^a-zA-Z0-9], where ^ - is meaning to look for any element which is not specified in [].
string a = "Today is a nice day, and I have been driving";
var res = a.Split();
List<string> groups = new List<string>();
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i=0;i< res.Length;i+=3)
{
string result = string.Empty;
try
{
result += rgx.Replace(res[i], "");
}
catch(Exception)
{
}
try
{
result +=" "+ rgx.Replace(res[i+1], ""); ;
}
catch (Exception)
{
groups.Add(result);
break;
}
try
{
result +=" "+ rgx.Replace(res[i + 2], "");
}
catch (Exception)
{
groups.Add(result);
break;
}
groups.Add(result);
}
foreach(var a1 in groups)
{
Console.WriteLine(a1);
}

How to read from file and make a HashMap [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 6 years ago.
Improve this question
Updated : to make it clear
I have txt file looks like this
a [456545324553645,43456765676564,62644456374,65768475336846,...]
b [3445324553645,4546465676564,07674456374,0906847534657,...]
c [21245324553645,43456765676564,62644456374,6576847534657,...]
d [133426545324553645,43456765676564,62644456374,6576847534657,...]
f [1243545324553645,43456765676564,62644456374,6576847534657,...]
g [356545324553645,43456765676564,62644456374,6576847534657,...]
I want to read the file and make a HashMap
that mean I want to store char in String variable as a Key of Hashmap
and store the numbers in String[] as Value of Hash-map
var lines = File.ReadAllLines("filename.txt");
var results = lines.Select(line => line.Split(' '))
.Select(split => new { Character = split[0], Number = split[1] });
// this is your data, now you can play with it
string allChars = string.Join(string.Empty, results.Select(r => r.Character));
string[] allNumbers = results.Select(r => r.Number).ToArray();
You need to read each line of a file, split it in two, then add each part to wherever it needs to go.
string character = "";
string[] numbers; //to be calculated at later
var numberList = new List<string>() // for ease of adding values
using(var file = File.OpenText(pathToFile))
{
while (!file.EndOfStream)
{
var lineParts = file.ReadLine().Split(' '); //split line around space characters
character += lineParts[0];
numberList.Add(lineParts[1]);
}
}
numbers = numberList.ToArray();
There are a couple of things to point out here that are good practice.
We don't know how big the file is (it could be thousands of lines), so we avoid reading the whole thing at once, instead, only read as much as you need at a time, in this case, a single line.
We're not adding straight to the array. Because of the above, we can't easily work out how many lines there are going to be, so we can't say how big the array needs to be. Instead we add to a List, and turn it into an array later. If you don't need the array, you don't even have to do that: you can just work with the list.
The line character += lineParts[0] isn't ideal: it creates extra String objects which then have to be thrown away. Instead, we could use a StringBuilder:
var characterBuilder = new StringBuilder();
...
characterBuilder.Append(lineParts[0]);
...
character = characterBuilder.ToString();
This becomes more relevant as your file gets bigger.
Update
If you want to create a hashmap, you're better off creating that from the beginning:
var numbers = new Dictionary<string, string>();
using(var file = File.OpenText(pathToFile))
{
while (!file.EndOfStream)
{
var lineParts = file.ReadLine().Split(" ".ToCharArray(), 2); //split line around space characters
numbers[lineParts[0]] = lineParts[1];
}
}
You'll note that I'm using a different overload of string.Split. It takes an int that specifies the maximum number of parts to produce.

C# - split string [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 9 years ago.
Improve this question
I have some problems with split and check string.
I need to split string, replace halfs and check is this the same as the second string.
example: first string = tokyo second string = koyto
soo... S = a+b = b+a
S - a = b and S - b = a
a and b is part of one string (S) and may have different long in this case a = to and b = koy
first I need to check string length - is the are different - then write Error - it's easy
the I thought that I can compare strings in ASCII (case sensitivity is not important) and it' could be ok but...
I can create string tooky which have got the same size in ASCII but is not created from split and invert parts of first string...
any ideas?
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
split string ?
}
else
Console.WriteLine("This two words are different. No result found.");
Console.Read();
}
I would suggest doing the comparisons with strings. You can use the String.ToLower() method to convert them both to lowercase for comparison.
I am not exactly sure what problem you are trying to solve is, but from what I understand you are trying to check if string S can be split into two substrings that can be rearranged to make string T.
To check this you will want something similar to the following
for (int i = 0; i < S.length; i++) {
string back = S.substring(i);
string front = S.substring(0,i);
if (T.equals(back + front))
result = true;
}
Hope this helps
If you want to compare equality of two collections you should consider using LINQ:
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
if (S.Intersect(T).Any())
{
Console.WriteLine("The Contents are the same");
Console.Read();
}
}
else
Console.WriteLine("This two words are diferent. No result found.");
Console.Read();
}

Moving 7+-letter words to file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
How can I move all words of seven letters or more in one string to another?
I know that I need a foreach loop to go through each character, and some sort of way of seeing whether the next character is blank while using a counter; then, if the next char is blank, see whether the counter is greater than or equal to seven, then move what was just there to a new string, then into a file.
You can use LINQ's Where method:
string strBigText = Console.ReadLine();
IEnumerable<string> words = strBigText.Split(" ").Where(o => o.Length >= 7);
This is going to split your text at every space, creating an array of strings, then retrieve only the elements (strings) that have a length greater than or equal to 7.
You could use string.split
string[] array = yourString.split(' ');
list<string> longStrings = new list<string>();
for(int i = 0; i < array.length; i++){
if(array[i].length >= 7){
longStrings.add(array[i]);
}
}
Something like that.
I would recommend RegExp for this (http://www.regular-expressions.info/).
At the top of your code, say:
using System.Text.RegularExpressions;
Then, in your routine, just go:
string input = textbox1.Text; // or wherever else you get your string from
MatchCollection matches = new Regex(#"(^|\b)\w{7}\w*(\b|$)").Matches(input);
string[] results = new string[matches.Count];
for (int i = 0; i != matches.Count; i++)
results[i] = matches[i];
//Now results will be an array of the 7-letter words.

Categories