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 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 5 years ago.
Improve this question
Suppose I have a file with multiple line:
En;15;
Vu;
US;32;
I need to check if the string VU is contained so I did:
string text = #"En;15;
Vu;
US;32;"
var exist = text.Contains("Vu");
this will return true but I need to check also if the line of Vu contains only Vu or other contents as the other lines. How can I do this? Thanks.
UPDATE
if the line contains also other element should return false
Split your string into an array and that you will be able to separate all the lines into a separated indexes in the string array using the Split() method
with the separator '\n' that represents a new line:
static void Main(string[] args)
{
string stringfromfile = #"En;
15;
Vu;
US;
32;";
string[] ar = stringfromfile.Split('\n');
// remove ";" character and fix white space for safety
for (int i = 0; i < ar.Length; i++)
{
ar[i] = ar[i].Replace(";","").Trim();
}
if (ar.Contains("Vu"))
{
Console.WriteLine("TRUE");
}
else
{
Console.WriteLine("FALSE");
}
foreach (var itm in ar)
{
Console.WriteLine(itm);
}
Console.ReadLine();
}
Assuming that in your input a "newline" is "\n", and assuming that things in a line are separated by ";", then:
1) break the text into separate lines
2) for each line, break the line into pieces separated by ";"
3) for each broken-line, check each piece and see if Vu is there
4) ..and if it is, hey you found it
5) ..and if that broken-line had just 1 piece, hey, it was single Vu
Bits of code:
1)
#"text
that
has
lines".Split("\n") ==> array of 4 lines
2)
"linethat;has;pieces".Split(";") ===> array of 3 pieces
3) "for each" is a foreach loop. You will need one for lines, and one for pieces. One inside the other.
4) Split removes the separator, so ";" wont show up in a piece, so if(piece == "Vu")
5) "pieces" is array-of-strings, so if(pieces.Length==1) means that the line had a single piece
Now you have all bits, just use them properly.
You could try searching very simply for "\nVu\n" so it would look something little like:
var exist = text.Contains("\nVu\n");
This would find all cases except for the special cases of first and last line, and is more efficient than splitting the string into an array.
And as #quetzalcoatl said
..and first and last line can be covered by .StartsWith("Vu\n") and .EndsWith("\nVu")..
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I guys im trying to workout C# code to extract the first two words from string. below is code im doing.
public static string GetDetailsAsString(string Details)
{
string Items = //how to get first 2 word from string???
if (Items == null || Items.Length == 0)
return string.Empty;
else
return Items;
}
Define "words", if you want to get the first two words that are separated by white-spaces you can use String.Split and Enumerable.Take:
string[] words = Details.Split();
var twoWords = words.Take(2);
If you want them as separate string:
string firstWords = twoWords.First();
string secondWord = twoWords.Last();
If you want the first two words as single string you can use String.Join:
string twoWordsTogether = string.Join(" ", twoWords);
Note that this simple approach will replace new-line/tab characters with empty spaces.
Assuming the words are separated by whitespaces:
var WordsArray=Details.Split();
string Items = WordsArray[0] + ' ' + WordsArray[1];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have a string which has a following format:
"####/xxxxx"
The text before the "/" is always an integer and I need to read it. How do I get only the integer part of this string (before the "/")?
Thank you for your help.
You can split the string on / and then use int.TryParse on the first element of array to see if it is an integer like:
string str = "1234/xxxxx";
string[] array = str.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
int number = 0;
if (str.Length == 2 && int.TryParse(array[0], out number))
{
//parsing successful.
}
else
{
//invalid number / string
}
Console.WriteLine(number);
Use IndexOf and Substring:
int indexOfSlash = text.IndexOf('/');
string beforeSlash = null;
int numBeforeSlash = int.MinValue;
if(indexOfSlash >= 0)
{
beforeSlash = text.Substring(0, indexOfSlash);
if(int.TryParse(beforeSlash, out numBeforeSlash))
{
// numBeforeSlash contains the real number
}
}
Another alternative: use a regular expression:
var re = new System.Text.RegularExpression(#"^(\d+)/", RegexOptions.Compiled);
// ideally make re a static member so it only has to be compiled once
var m = re.Match(text);
if (m.IsMatch) {
var beforeSlash = Integer.Parse(re.Groups[0].Value);
}