Insert blank strings into array based on index - c#

Let's say I have an array for example
string[] A = {"1","2","3","4","5"}
I want the array to be of size 10, and want to insert blank strings after a certain index.
For example, I could make it size 10 and insert strings after index 3 which would result in
A = {"1","2","3","4","","","","","","5"}
Basically the elements after the given index will be pushed to the end and blank strings will take the empty space in between.
This is what I tried but it only adds one string and doesnt exactly set a size for the array
var foos = new List<string>(A);
foos.Insert(33, "");
foos[32] = "";
A = foos.ToArray();

You can use InsertRange
var l = new List<string>{"1","2","3","4","5"};
l.InsertRange(3, new string[10 - l.Count]);
foreach(var i in l)
Console.WriteLine(i);
Note: The above doesn't populate with empty strings but null values, but you can easily modify the new string[] being used to be populated with your desired default.
For example; see How to populate/instantiate a C# array with a single value?

Here is LINQ based approach:
public string[] InsertToArray(string[] array, int index, int newArrayCapacity)
{
var firstPart = array.Take(index + 1);
var secondPart = array.Skip(index + 1);
var newPart = Enumerable.Repeat(String.Empty, newArrayCapacity - array.Length);
return firstPart.Concat(newPart).Concat(secondPart).ToArray();
}
Here is the usage of the method:
string[] A = {"1","2","3","4","5"};
// Insert 5 elements (so that A.Length will be 10) in A after 3rd element
var result = InsertToArray(A, 3, 10);
Added: see Sayse's answer, really the way to go

Since arrays are fixed sized collections, you can't resize an array.What you need to do is to split your array elements, you need to get the elements before and after the specified index,you can do that by using Skip and Take methods, then you need to generate a sequence of empty strings and put them together:
string[] A = {"1","2","3","4","5"};
int index = 3;
var result = A.Take(index + 1)
.Concat(Enumerable.Repeat("", 10 - A.Length))
.Concat(A.Skip(index+1))
.ToArray();

If you don't mind using a list instead of an array, you can do it this way:
int index = 3;
int numberOfBlanksToInsert = 5;
List<string> strings = new List<string>();
for (int i = 0; i < numberOfBlanksToInsert; i++)
{
strings.Insert(index, "");
}
You can also output this to an array when you're done:
string[] A = strings.ToArray();

static string[] InsertRange(string[] initialValues, int startIndex, int count, string toInsert)
{
string[] result = new string[initialValues.Length + count];
for (int i = 0; i < initialValues.Length + count; i++)
result[i] = i < startIndex ? initialValues[i] : i >= startIndex + count ? initialValues[i - count] : toInsert;
return result;
}
Usage : InsertRange(A, 4, 5, "hello");
Output : "1, 2, 3, 4, hello, hello, hello, hello, hello, 5"

Related

How can I start a splitted string from index 1 instead of 0?

I have the following code, which reads a line from the console:
// Read text from input
var inputText = Console.ReadLine();
var inputTextSplit = inputText.Split(' ');
A possible input might be: Hello my name is John. If I try to iterate over this input now, "Hello" will be the first index (0). So inputTextSplit[0] will be equal to Hello, inputTextSplit[1] will be equal to "my", etc. What I'm trying to achieve is a way to make the index counting start at 1. So I want inputTextSplit[0] to have no value (or any filler value), and inputTextSplit[1] be "Hello", inputTextSplit[2] be "my", etc.
There are many ways to do this, here are a few
Given
var inputText = Console.ReadLine();
Simply putting an extra space on the start
var inputTextSplit = (" " + inputText).Split(' ')
Converting to List and using Insert, then converting back to an Array
var inputTextSplit = inputText.Split(' ').ToList();
inputTextSplit.Insert(0,null);
var result = inputTextSplit.ToArray();
Allocating a new array, the using Array.Copy
var inputTextSplit = inputText.Split(' ');
var result = new string[inputTextSplit.Length + 1];
Array.Copy(inputTextSplit, 0, result, 1, inputTextSplit.Length);
Resizing the array, and nulling the first element
Array.Resize(ref inputTextSplit, inputTextSplit.Length + 1);
Array.Copy(inputTextSplit, 0, inputTextSplit, 1, inputTextSplit.Length - 1);
inputTextSplit[0] = null;
using a Span.. just for giggles
var inputTextSplit = Console.ReadLine().Split(' ');
var result = new string [inputTextSplit.Length + 1];
inputTextSplit.AsSpan().CopyTo(new Span<string>(result)[1..]);
Your own iterator method
public static class Extensions
{
public static IEnumerable<string> MyOwnFunkySplit(this string source)
{
yield return null;
foreach (var item in source.Split(' '))
yield return item;
}
}
...
var inputTextSplit = Console
.ReadLine()
.MyOwnFunkySplit()
.ToArray();
You can't - split will always put the first segment into the first element of the array, which indeed has index 0.
If you really need the first segment to be at index 1 you can:
alter starting string to always have extra value
var inputTextSplit = ("skip " + inputText).Split(' ');
if you just need an enumerable where first element does not matter - concat with empty array:
var startingAtOne = (new[]{"skip"}).Concat(inputTextSplit);
copy array to a new one with an extra element at the beginning - Insert a element in String array
var startingAtOne = (new[]{"skip"}).Concat(inputTextSplit).ToArray();
Note that it is a very strange requirement and probably should be addressed in code that consumes the result.

C# Array Different indexes

Hi i want to search for character in a string array but i need to search Between 2 indices. For example between index 2 and 10. How can I do that?
foreach (var item in currentline[2 to 10])
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
As you can see, foreach enumerates over a collection or any IEnumerable.
As the comments say, you can use a for loop instead, and pick out the elements you want.
Alternatively, since you want to search for a character in a string, you can use IndexOf, using the start index and count overload to find where a character is.
As there is no use of the c++ in your code I will assume that it's a vestige of code.
You can simply addess your issue like this:
In the currentline
Take char from index 2 to 10
Till you find a char you don't want.
concatenate the resulting char array to a string.
Resulting Code:
var data = "##";//01234567891 -- index for the string below.
var currentline= "kj[abcabc;z]Selected data will be between: '[]';";
var exceptChar = ",;";
data += new string(
input.Skip(3)
.Take(8)
.TakeWhile(x=> !exceptChar.Contains(x))
.ToArray()
);
There is a string method called string.IndexOfAny() which will allow you to pass an array of characters to search for, a start index and a count. For your example, you would use it like so:
string currentLine = ",;abcde;,abc";
int index = currentLine.IndexOfAny(new[] {',', ';'}, 2, 10-2);
Console.WriteLine(index);
Note that the last parameter is the count of characters to search starting at the specified index, so if you want to start at index 2 and finish at index 10, the count will be finish-start, i.e. 10-2.
You can search for characters in strings and get their indexes with this LINQ solution:
string str = "How; are, you; Good ,bye";
char[] charArr = { ',', ';' };
int startIndex = 2;
int endIndex = 10;
var indexes = Enumerable.Range(startIndex, endIndex - startIndex + 1)
.Where(i=>charArr.Contains(str[i]))
.ToArray();
In this case we get Enumerable.Range(2, 9) which generates a sequence between 2 and 10 and the Where clause filters the indexes of the characters in str that are matching one of the characters inside charArr.
Thanks everey one finaly i fixed it by your guid thanks all
myarr = new mytable[50];
number_of_records = 0;
number_of_records = fulllines.Length;
for (int line = 1; line < fulllines.Length; line++)
{
int c = 0;
for (int i = 0; i < record_lenth; i++)
{
string data = "";
string currentline = fulllines[line];
string value = "";
for (int x = c; x < fulllines[line].Length; x++)
{
value += currentline[x];
}
foreach (var item in value)
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
}
}

String split by every 3 words

I've got a problem. I need to split my every string like this:
For example:
"Economic drive without restrictions"
I need array with sub string like that:
"Economic drive without"
"drive without restrictions"
For now i have this:
List<string> myStrings = new List<string>();
foreach(var text in INPUT_TEXT) //here is Economic drive without restrictions
{
myStrings.DefaultIfEmpty();
var textSplitted = text.Split(new char[] { ' ' });
int j = 0;
foreach(var textSplit in textSplitted)
{
int i = 0 + j;
string threeWords = "";
while(i != 3 + j)
{
if (i >= textSplitted.Count()) break;
threeWords = threeWords + " " + textSplitted[i];
i++;
}
myStrings.Add(threeWords);
j++;
}
}
You could use this LINQ query:
string text = "Economic drive without restrictions";
string[] words = text.Split();
List<string> myStrings = words
.Where((word, index) => index + 3 <= words.Length)
.Select((word, index) => String.Join(" ", words.Skip(index).Take(3)))
.ToList();
Because others commented that it would be better to show a loop version since OP is learning this language, here is a version that uses no LINQ at all:
List<string> myStrings = new List<string>();
for (int index = 0; index + 3 <= words.Length; index++)
{
string[] slice = new string[3];
Array.Copy(words, index, slice, 0, 3);
myStrings.Add(String.Join(" ", slice));
}
I try to give a simple solution. So i hope you can better understand it.
List<string> myStrings = new List<string>();
string input = "Economic drive without restrictions";
var allWords = input.Split(new char[] {' '});
for (int i = 0; i < allWords.Length - 2; i++)
{
var textSplitted = allWords.Skip(i).Take(3);
string threeString = string.Join(" ", textSplitted);
myStrings.Add(threeString);
}
foreach (var myString in myStrings)
{
Console.WriteLine(myString);
}
The method Take(n) is from Linq. It takes the first n elements of the given array. for example if you have an array a,b,c,d,e then Take(3) will give you a new array a,b,c.
The method Skip(n) is from Linq. It gives you the new array by skipping first n elements. given array a,b,c,d,e then Skip(1) will return b,c,d,e. as you can see it skipped the first elements.
Now with this two methods you can move on array 3 by 3 and get the words you want.
Just for comparative purposes, here's another solution that doesn't use Linq:
string[] words = INPUT_TEXT.Split();
List<string> myStrings = new List<string>();
for (int i = 0; i < words.Length - 2; ++i)
myStrings.Add(string.Join(" ", words[i], words[i+1], words[i+2]));
Or using ArraySegment<string>:
string[] words = INPUT_TEXT.Split();
List<string> myStrings = new List<string>();
for (int i = 0; i < words.Length - 2; ++i)
myStrings.Add(string.Join(" ", new ArraySegment<string>(words, i, 3)));
I would use one of the methods described here ; for instance the following that takes the elements 3 by 3.
var groups = myStrings.Select((p, index) => new {p,index})
.GroupBy(a =>a.index/3);
Warning, it is not the most memory efficient, if you start parsing big strings, it might blow up on you. Try and observe.
Then you only need to handle the last element. If it has less than 3 strings, fill it up from the left.

c# string concat to get another variable

Good day. I would like to ask if it is possible to concatenate 2 strings to get another variable.
Lets say I have this code:
string num1 = "abcdefgh";
string num2 = "ijklmnop";
int numLength = 0;
And I want to get the value of both num1 and num2 using a forloop
for(int i =1; i<= 2; i++)
{
numLength = ("num" + i).Length + numLength;
}
Console.WriteLine("Length is {0}", numLength);
I want it to output
Length is 16
I did the above code but it actually gives me different value.
Edit1: (P.S. I will be using more than 10 variables, I just indicated 2 of it to make it simple)
Edit2: Yes, yes. I want ("num"+i).Length to give me num1.Legnth + num2.Length.
First way:
I suggest you to add all of your strings into the List and then get the total length with Sum method.
List<string> allStrings = new List<string>();
allStrings.Add(num1);
allStrings.Add(num2);
...
allStrings.Add(num10);
var totalLength = allStrings.Sum(x => x.Length);
Second way
Or if you want to calculate total length with for loop:
int totalLength = 0;
for (int i = 0; i < allStrings.Count; i++)
{
totalLength = totalLength + allStrings[i].Length;
}
Third way
If you don't want to use List, then you can use String.Concat and then Length property.
var totalLength = String.Concat(num1, num2).Length;
The result is 16 in your case.
Edit:
In my opinion you think that, ("num" + i).Length will give you num1.Length and num2.Length. This is wrong.
Lets say we have some strings and we want the total length for all this strings.
In this case you need to store all strings in an array, so you can counter them and use indexes.
and after that a simple for (or foreach) loop can solve the problem:
string[] texts = new string[20]; //You can use any number u need, but in my code I wrote 20.
texts[0] = "sample text 1";
texts[1] = "sample text 2";
// add your strings ...
int totalLenght = 0;
foreach (string t in texts)
{
totalLenght += t.Length;
}
Console.WriteLine("Length is {0}", totalLenght);
If you need a variable with unlimited size, use List<T>
here is example:
List<string> texts = new List<string>();
texts.Add("sample text 1");
texts.Add("sample text 2");
// add your strings ....
int totalLenght = 0;
for (int i = 0; i < texts.Count; i++)
{
totalLenght += texts[i].Length;
}
Console.WriteLine("Length is {0}", totalLenght);

String to array

I have a string :
id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx
I just need the value for idX-value from the string into array.
How can I achieve it?
The simple way, the value is in position (4x - 1):
var list = input.Split(':');
var outputs = new List<string>();
for (int index = 0; index < list.Count(); index++)
{
if (index % 4 == 3)
outputs.Add(list.ElementAt(index));
}
Use String.Split()
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
String myString = "id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx";
String[] tokens = myString.Split(new Char[] {':'});
The token array will contain {"id0","xxxxx","id0-value","xxxxx","id1","xxxxxxxx","id1-value","xxxxx","id3","xxxxxxxx","d3-value","xxx"}
The second possibility is to use String.IndexOf() and String.Substring().
http://msdn.microsoft.com/en-us/library/5xkyx09y
http://msdn.microsoft.com/en-us/library/aka44szs
Int start = 0;
ArrayList tokens;
while((start = myString.IndexOf("-value:", start)) > -1) {
ArrayList.Add(myString.Substring(start+6, myString.IndexOf(":", start+7);
start += 6; // Jump past what we just found.
}
Split it using a Regex(a regex which splits : coming after x), then split using colon : and use first index as a Dictionary Key and Second index as Dictionary value.

Categories

Resources