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);
Related
I have huge string e.g (This is just the part, the string looks same it has just a bit different values).
string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";
So I have to swap the whole number e.g.
Output should be:
9.16364437205161 48.7465504247904
Also I need to swap the first and second part.
So I've tried to split the string, and then to replace the old one with the new one.
string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";
string output = "";
double first = 0;
double second = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers.Split(' ');
first = numbers[0];
second = numbers[1];
}
output = numbers.Replace(numbers[1], numbers[0]);
Console.WriteLine(output);
But my variable first always after the loop has the value 52.
Right now my output is: 44.7465504247904 9.16364437205161, it changed the first part, also it calculates somehow -4
.
You're not assigning anything to the value coming back from .Split and, if I read this right, you're also iterating each character in the numbers array for unclear reasons.
Using .Split is all you need ... well, and System.Linq
using System.Linq;
// ...
string SwapNumbers(string numbers) {
return numbers.Split(' ').Reverse().Join();
}
The above assumes you want to reverse the whole series of numbers. It absolutely does not swap 1,2 then swap 3,4 etc. If that's what you're looking for, it's a bit more involved and I'll add that in a second for funsies.
string SwapAlternateNumbers(string numbersInput) {
var wholeSeries = numbersInput.Split(' ').ToList();
// odd number of inputs
if (wholeSeries.Count % 2 != 0) {
throw new InvalidOperationException("I'm not handling this use case for you.");
}
var result = new StringBuilder();
for(var i = 0; i < wholeSeries.Count - 1; i += 2) {
// append the _second_ number
result.Append(wholeSeries[i+1]).Append(" ");
// append the _first_ number
result.Append(wholeSeries[i]).Append(" ");
}
// assuming you want the whole thing as a string
return result.ToString();
}
Edit: converted back to input and output string. Sorry about the enumerables; that's a difficult habit to break.
here
public static void Main()
{
string nums = "48.7465504247904 9.16364437205161 48.7465504247904 9.16364437205161";
var numbers = nums.Split(' ');
var swapped = numbers.Reverse();
Console.WriteLine("Hello World {"+string.Join(" ",swapped.ToArray())+"}");
}
Hi sorry guys I'm pretty new to C# and programming in general.
I have a text file that I'm reading from which contains 10 lines (all but the first of which are relevant).
I want to split each line (besides the first since it's only one word) by the commas, then retrieve the 5th one along of each line, adding it to a total.
Currently all I have been able to do is essentially split and add the same value to the total 10 times, instead of adding the 9 different values together, or face a "System.IndexOutOfRangeException".
int totalValues = 0;
string[] larray = lines.ToArray(); //create array from list
string vehicleValue;
for (int i = 0; i < larray.Length; i++)
{
string[] bits = larray[i].Split(',');
vehicleValue = bits[4];
int vvint = int.Parse(vehicleValue);
totalValues = totalValues + vvint;
}
totalValue.Text = totalValues.ToString();
As it stands, the above code results in a "System.IndexOutOfRangeException" highlighting "vehicleValue = bits [4];"
Every line of the file looks like this, besides the first one.
Car,Ford,GT40,1964,250000,987,Red,A1,2,4,FALSE
The value I want out of this specific line would be '250000' - the 5th one along. I'm trying to get the 5th one along from every line.
Your problem is that you are trying to parse also the first line (which does not contain enough entries so you get the exception). You can skip the first line by starting your iteration at index 1:
int totalValues = 0;
string[] larray = lines.ToArray(); //create array from list
string vehicleValue;
for (int i = 1; i < larray.Length; i++)
{
string[] bits = larray[i].Split(',');
vehicleValue = bits[4];
int vvint = int.Parse(vehicleValue);
totalValues = totalValues + vvint;
}
totalValue.Text = totalValues.ToString();
bits[4] is the fifth item in the array as indexing starts from zero, to get the fourth item you should get bits[3]
int totalValues = 0;
string[] larray = lines.ToArray(); //create array from list
string vehicleValue;
for (int i = 0; i < larray.Length; i++)
{
string[] bits = larray[i].Split(',');
vehicleValue = bits[3];
int vvint = int.Parse(bits[3]);
totalValues = totalValues + vvint;
}
totalValue.Text = totalValues.ToString();
I am developing in C#.
I have a text file containing the following:
Sam
NYC
Mii
Peru
LEO
Argentina
I want to iterate through this file two line by two line, then print to the console the first line, second line (the Name and the Country) of each couple, so the output would be:
Sam, NYC
Mii, Peru
Here is what I have tried:
int linenum = 0;
foreach (string line in File.ReadLines("c:\\file.txt"))
{
string word = line;
string s = "";
string j = "";
linenum = linenum + 1;
if(linenum % 2 != 0) //impaire
{
s = line;
}
else
{
j = line;
}
Console.WriteLine((string.Concat(s, j));
}
But that's not working, I want to do:
int linenum = 0;
foreach( two lines in File.ReadLines("c:\\file.txt"))
{
linenum = linenum + 1;
//get the first line (linenum = 1) and store it in a string s
// then get the second line (linenum = 2) and store it in a string j
// then print the two strings together to the console like that
Console.WriteLine((string.Concat("S: " + s,"J: " j));
}
How can I do that ?
Use File.ReadAllLines to return an array of strings:
var lines = File.ReadAllLines(filePath);
for (int i = 0; i < lines.Length; i+=2)
{
var s = lines[i];
var j = lines[i+1];
Console.WriteLine($"S: {s} J: {s}");
}
You do your output with Console.WriteLine in every line, but you also should do that only for every second line. Furthermore, your variables s and j live inside the loop's scope, so they are recreated with every iteration and loose their prior value.
int i = 0; string prev = "";
foreach (string line in File.ReadLines("c:\\file.txt")) {
if (i++ % 2 == 0) prev = line;
else Console.WriteLine($"{prev}, {line}");
}
Another approach would be iterating the array you get from File.ReadAllLines with an for loop instead of foreach and increase the index by 2
var lines = File.ReadAllLines("c:\\file.txt");
//make sure, you have an even number of lines!
if (lines.Length% 2 == 0) for (int i = 0; i < lines.Length; i+=2) {
Console.WriteLine($"{lines[i]}, {lines[i+1]}");
}
You can write yourself a little helper method to return batches of lines.
This implementation handles files that are not a multiple of the batch size (2 in your case) by returning "" for the missing lines at the end of the file.
public static IEnumerable<string[]> BatchedLinesFromFile(string filename, int batchSize)
{
string[] result = Enumerable.Repeat("", batchSize).ToArray();
int count = 0;
foreach (var line in File.ReadLines(filename))
{
result[count++] = line;
if (count != batchSize)
continue;
yield return result;
count = 0;
result = Enumerable.Repeat("", batchSize).ToArray();
}
if (count > 0)
yield return result;
}
Note that this also returns a separate array for each result, in case you make a copy of it.
Given that code, you can use it like so:
foreach (var batch in BatchedLinesFromFile(filename, 2))
{
Console.WriteLine(string.Join(", ", batch));
}
Actually, you can use LINQ to get two lines in a time using Take
var twoLines = File.ReadLines(#"YourPath").Take(2));
As you can use Skip to skip the two lines you took and take the next two lines like :
var twoLines = File.ReadLines(#"YourPath").Skip(2).Take(2));
EDIT : Thanks for #derpirscher there were a performance issue so changed the code to the following :
first read the whole file and store it in a string array
then loop through it using LINQ to take two elements from the array in a time.
string[] myStringArray = File.ReadAllLines(#"YourFile.txt");
for (int i = 0; i < myStringArray.Length ; i+=2)
{
var twoLines = myStringArray.Skip(i).Take(2).ToArray();
}
Another one, using Enumerable.Repeat() and an interger selector incremented a [NumberOfLines / 2] times.
Could be interesting for the LINQ addicted (a for / foreach solution is probably better anyway).
string[] input = File.ReadAllLines([SourcePath]);
int Selector = -1;
string[] output = Enumerable.Repeat(0, input.Length / 2).Select(_ => {
Selector += 2;
return $"{input[Selector - 1]} {input[Selector]}";
}).ToArray();
The output is:
Sam NYC
Mii Peru
LEO Argentina
Use the right tool for the job. foreach() is not the right tool here.
Without giving up the memory efficiency of ReadLines() over ReadAll():
using (var lines = File.ReadLines("c:\\file.txt").GetEnumerator())
{
while (lines.MoveNext())
{
string firstLine = lines.Current;
if (!lines.MoveNext())
throw new InvalidOperationException("odd nr of lines");
string secondLine = lines.Current;
// use 2 lines
Console.WriteLine("S: " + firstLine ,"J: " + secondLine);
}
}
I need to set a new string and that the user need to set this new string name
for example:
int input = 0;
while (input != -1)
{
input = int.Parse(Console.ReadLine());
int count = 0;
count ++;
int ("the " count)= intput;
}
You don't want a "dynamic variable", you want a dictionary. Something like this:
Dictionary<int, int> values = new Dictionary<int, int>();
int count = 0;
int input = 0;
while (input != -1)
{
input = int.Parse(Console.ReadLine());
count++;
values.Add(count, input);
}
You can do your "the" part in some output if you need to, but the values being stored in this case appear to be just int values anyway. If you want to get creative you can wrap some data types in a custom class and output formatted strings from that class easily enough.
Another change to note above is moving the declaration of count outside of the loop, otherwise it's always going to be 1.
Basically, just about any time you find yourself wanting a dynamic variable name following some pattern, what you actually want is a collection of some kind. Maybe a dictionary, maybe a list, maybe something else, etc.
I think, that is, waht do ypu need:
int input = 0;
var inputs = new List<int>();
while (input != -1)
{
input = int.Parse(Console.ReadLine());
int count = 0;
count++;
inputs.Add(input);
}
var result = inputs.Select((j, i) => Tuple.Create("The " + i, j)).ToList();
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"