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"
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I have a string "ABD-DDD-RED-Large" and need to extract "DDD-RED"
using the Split I have:
var split = "ABD-DDD-RED-Large".Split('-');
var first = split[0];
var second = split[1];
var third = split[2];
var fourth = split[3];
string value = string.Join("-", second, third);
just wondering if there's a shorter code
If you just want the second and third parts of an always 4 part (delimited by -) string you can one line it with LINQ:
string value = string.Join("-", someInputString.Split('-').Skip(1).Take(2));
An input of: "ABD-DDD-RED-Large" would give you an output of: "DDD-RED"
Not enough information. You mentioned that string is not static. May be Regex?
string input = "ABD-DDD-RED-Large";
string pattern = #"(?i)^[a-z]+-([a-z]+-[a-z]+)";
string s = Regex.Match(input, pattern).Groups[1].Value;
Use regex
var match = Regex.Match(split, #".*?-(.*?-.*?)-.*?");
var value = match.Success ? match.Groups[1].Value : string.Empty;
I'm going out on a limb and assuming your string is always FOUR substrings divided by THREE hyphens. The main benefit of doing it this way is that it only requires the basic String library.
You can use:
int firstDelIndex = input.IndexOf('-');
int lastDelIndex = input.LastIndexOf('-');
int neededLength = lastDelIndex - firstDelIndex - 1;
result = input.Substring((firstDelIndex + 1), neededLength);
This is generic enough to not care what any of the actual inputs are except the hyphen character.
You may want to add a catch at the start of the method using this to ensure there are at least two hyphen's in the input string before trying to pull out the requested substring.
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
ok I have no idea on how to do this and i have tried looking up how to do this but nothing good came up so ill ask it here. So what i am trying to do is:
string input = TextEditor.text; <-- this is in windows form application and
The "TextEditor" is the textbox for input
i want to take the string (which is input from the texct box) then split it so each word is on every other line like so:
if input = "hi my name is is"
out put should be:
hi: 1
my: 1
name: 1
is: 2 <-- if the word is said it shouldn't be repeated.
could someone please help me? I am a true newbie and i am completely lost. I don't have any code yet because I DONT KNOW HOW TO DO THIS!
Use Linq GroupBy and Count:
string inputText = "hi my name is is";
var words = inputText.Split(' ').ToList();
var wordGroups = words.GroupBy(w => w).Select(grp => new {
Word = grp.Key,
Count = grp.Count()
});
string outputText = string.Join("\n", wordGroups.Select(g => string.Format("{0}:\t{1}", g.Word, g.Count)));
/*
hi: 1
my: 1
name: 1
is: 2
*/
Split the input string into an array, then use that to build a dictionary. If the word is already in the dictionary, increment it. Otherwise add it with an initial value of 1.
string input = TextEditor.text;
string[] inputWords = input.Split(' ');
Dictionary<string, int> wordCounts = new Dictionary<string, int>();
foreach (string word in inputWords)
{
if (wordCounts.ContainsKey(word))
{
wordCounts[word]++;
}
else
{
wordCounts.Add(word, 1);
}
}
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need to search through a string array to find every occurrence of "Parameters Table", and between each "Parameters Table" and the next, get another string from a specified index (that remains constant). I have been doing this like so:
public List<string> findlistOfNames(string[] arrayToLookForNames)
{
List<string> listOfNames = new List<string>();
const string separator = "Parameters Table"; //This is the string I am searching for
var cuttedWords = arrayToLookForNames.SkipWhile(x => x != separator).Skip(1);
while (cuttedWords.Any())
{
var variable = cuttedWords.TakeWhile(x => x != separator).ToArray();
cuttedWords = cuttedWords.Skip(variable.Length + 1);
listOfNames.Add(variable[2]); //This (always index 2) needs to be added to the list
}
return listOfNames;
}
This runs very slowly. Is there a better way to do this?
EDIT: Here is a snippet of string[] arrayToLookForNames:
Parameters Table
0
41
Baro Pressure
hPa
AFD2
recorded
Parameters Table
0
42
Baro Setting
in-hg
Seeing as you haven't specified what happens in the following case:
Parameters TableewfihweifhweParameters TableihwefwihewfParameters Table
where there are a total of 3 possible matches, I've chosen to assume that there's only one match per entry.
You could use regular expressions to state this somewhat more succinctly. Will probably be more efficient than your method too...
var regex = new Regex(#"(?<=Parameters Table).*?(?=(?:Parameters Table)|$)");
IEnumerable<string> foundValues =
arrayToLookForNames.SelectMany(x => regex.Matches(x))
.Where(m => m.Success)
.Select(m => m.Value);
... for the entry above, this would yield ewfihweifhwe
to cater for your better specified requirements:
var regex = new Regex(#"(?<=Parameters Table).*?(?=(?:Parameters Table)|$)",
RegexOptions.Singleline);
var vals = arrayToLookForNames
.SelectMany(x=>regex.Matches(x).Cast<Match>())
.Where(m=>m.Success)
.Select(m=>m.Value);