Mix 2 strings that do not have the same length? [duplicate] - c#

This question already has answers here:
Add two Lists of different length in C#
(14 answers)
Merge different length arrays without losing a value using Zip()
(3 answers)
Closed 9 months ago.
I'm trying to mix two strings like this:
string a1 = "123456";
string a2 = "DFEG";
var builder = new StringBuilder();
for (int i = 0; i < a1.Length; i++)
{
builder.Append(a1[i]);
builder.Append(a2[i]);
}
Console.WriteLine(builder.ToString());
I want the output to be "1D2F3E4G56".
It works if both strings are the same lengths, but not if they're different lengths.

int maxIndex = a1.Length > a2.Length ? a1.Length : a2.Length;
for (int i = 0; i < maxIndex; i++)
{
if(a1.Length > i)
builder.Append(a1[i]);
if(a2.Length > i)
builder.Append(a2[i]);
}

The array access here will result in out of bounds exception
Use Enumerable.ElementAtOrDefault to attempt accessing the array at that index, or have it use that type's default value if said index is out of bounds
Since these are of the string type, the default value will be "" or string.empty which is perfectly acceptable for your situation as it won't alter the string you want to return
builder.Append(a1.ElementAtOrDefault(i));
builder.Append(b1.ElementAtOrDefault(i));

This will work for you. Good luck
string a1 = "123456";
string a2 = "DFEGfgg";
MixStrings(a1,a2);
public void MixStrings(string a, string b)
{
var builder = new StringBuilder();
builder.Append("");
for (int i = 0; i < (a.Length > b.Length ? a.Length : b.Length); i++)
{
builder.Append(a.Length>i?a[i]:"");
builder.Append(b.Length>i?b[i]:"");
}
Console.WriteLine(builder.ToString());
}

Related

C# Define Variables using Loop [duplicate]

This question already has answers here:
Create dynamic variable name
(5 answers)
Closed last year.
Ok this might be a weird question and I don't really know how to phrase it so I just show you an example:
int i = 0;
int k = 100;
while (i <5) {
***response+i*** = k + i;
i++;
}
I want to declare multiple Variables (response1, response2, respons3 ...) using a loop, so that in the end the result is:
response1 = 101
response2 = 102
response3 = 103
etc.
I am still a beginner at C# and programming in general, so I don't know if that is even possible how I imagine it, hope you can help me, thanks.
First, You can not define a variable by using two variable. That is not how compiler work.
Maybe you should try to create a Array or List to store the value
like this example
int i = 0;
int k = 100;
int[] response = new int[100];
while (i < 5)
{
response[i] = k + i;
i++
}
if you don't know the array size you want , try to do with List
List<int> response = new List<int>();
int i = 0;
int k = 100;
while (i < 5)
{
response.Add(i + k);
i++;
}
You should really use an array for these values, it's not really possible to use dynamic variable names.
I would also use a for loop where you need the index variable rather than having to manually update it in the while loop.
var results = int[5];
int k = 100;
for (var i = 0; i < results.Length; i++)
results[i] = k + i;

c# user input array for integer to look for specific number

Im new to programming i use c# to solve some problem but i have problem when user input two integer no in same-line and i want to look for zero and remove it from each no i think by replacing with the next array cell i should convert integer to string again but i cant do it please help me
string[] arr = Console.ReadLine().Split(' ');
string a = arr[0];
string b = arr[1];
int[] m = new int[1];
int[] n = new int[1];
for (int i = 0; i < a.Length; i++)
{
if (a[i] == 0 && a[a.Length - 1] != 0)
{
for (int j = i; j < a.Length; j++)
{
//****m[i] = int.Parse(a[i]); the error here cant convert from char to string ??
// a[i] = a[i + 1];**\\ Error CS0200 Property or indexer 'string.this[int]' cannot be assigned to -- it is read only**
I don't really know what you're trying to do, but if you're trying to convert the char into an ASCII value, then you would have to use the static method of Char called GetNumericValue.
Information on GetNumericValue can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.char.getnumericvalue?view=netcore-3.1

Capturing user input for an array in C# [duplicate]

This question already has answers here:
how can read values and put them in Array C#
(3 answers)
Closed 3 years ago.
I have been messing around with Lambda expressions in C#, teaching myself, and trying to test myself here. The problem with my code is not in evaluating the array for these set conditions, but rather I am having a difficult time capturing user input to build out the array. Have tried a few different methods, some mentioned here, but seem to have trouble adapting them to my code. Also any input on simplifying my expressions for checking if it has odd only or even only would be appreciated! I feel they are slightly bloated. Thanks!
using System;
namespace BuildingArrays
{
class Program
{
static void Main(string[] args)
{
int[] numbers = {Int32.TryParse(string, Console.ReadLine())};
bool hasOddOnly = Array.Exists(numbers, (int num) =>
{
bool hasEven = num % 2 == 0;
return hasEven;
});
hasOddOnly = !hasOddOnly;
bool hasEvenOnly = Array.Exists(numbers, (int num) =>
{
bool hasOdd = num % 2 != 0;
return hasOdd;
});
hasEvenOnly = !hasEvenOnly;
bool hasOddAnd4 = Array.Exists(numbers, (int num) =>
{
bool hasOdd = num % 2 != 0;
bool is4 = num == 4;
return is4 && hasOdd;
});
bool multipleOf4 = Array.Exists(numbers, (int num)=>
{
bool multiple = num % 4 == 0;
bool multiple2 = num % 3 == 0;
return multiple || multiple2;
});
bool multipleOf4and3 = Array.Exists(numbers, (int num)=>
{
bool multipleBoth = num % 4 == 0 && num % 3 == 0;
return multipleBoth;
});
Console.WriteLine($"This array contains odd numbers and 4 is {hasOddAnd4}");
Console.WriteLine($"This array contains ONLY odd numbers is {hasOddOnly}.");
Console.WriteLine($"This array contains ONLY even numbers is {hasEvenOnly}.");
Console.WriteLine($"This array contains either a multiple of 4, or a multiple of 3 is {multipleOf4}.");
Console.WriteLine($"This array contains a number which is both a multiple of 4 and 3 is {multipleOf4and3}");
}
}
}
Array.Exists takes a Predicate<T> as the second parameter. That should look like this:
bool hasEven = Array.Exists(numbers, x => x % 2 == 0);
To fill your array, you're going to need something like this:
for (int i=0; i< numbers.Length; i++)
numbers[i] = Int32.Parse(Console.ReadLine());
Further Reading
Array.Exists on MSDN
How to fill an array from user input in C#

Converting an integer to an array of digits [duplicate]

This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
I want to know if there is a way in C# to convert an integer to an array of digits so that I can perform (Mathematical) operations on each digit alone.
Example: I need the user to input an integer i.e 123, 456
then the program creates two arrays of three elements {1,2,3}, {4,5,6}.
Off the top of my head:
int i = 123;
var digits = i.ToString().Select(t=>int.Parse(t.ToString())).ToArray();
You could create such array (or List) avoiding string operations as follows:
int x = 123;
List<int> digits = new List<int>();
while(x > 0)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits.Add(digit);
}
digits.Reverse();
Alternative without using the List and the List.Reverse:
int x = 456;
int[] digits = new int[1 + (int)Math.Log10(x)];
for (int i = digits.Length - 1; i >= 0; i--)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits[i] = digit;
}
And one more way using ToString:
int x = 123;
int[] digits = Array.ConvertAll(x.ToString("0").ToCharArray(), ch => ch - '0');
You can use this and not convert to a string:
var digits = new List<int>();
var integer = 123456;
while (integer > 0)
{
digits.Add(integer % 10);
integer /= 10;
}
digits.Reverse();

Get number inside of a string and do a loop

I want to get a number of a string, and separate the string and the number, and then, do a loop and call a method the number of times the string says.
The string has to have this structure: "ABJ3" (Only one number accepted and 3 characters before it)
This is my code, but it repeat hundred of times, I don't know why
int veces = 0;
for (int i = 0; i < m.Length; i++)
{
if (Char.IsDigit(m[i]))
veces = Convert.ToInt32(m[i]);
}
if (m.Length == 4)
{
for (int i = 0; i <= veces; i++)
{
m = m.Substring(0, 3);
operaciones(m, u, t);
Thread.Sleep(100);
}
}
operaciones(m,u,t);
if (u.Length >= 14)
{
u = u.Substring(0, 15);
}
Some help please?
You have to convert your m[i] ToString() right now you are sending the char value to Convert.ToInt32 and that is a much higher value (9 = 57 for example)
char t = '9';
int te = Convert.ToInt32(t.ToString());
Console.WriteLine(te);
This gives us a result of 9 but
char t = '9';
int te = Convert.ToInt32(t);
Console.WriteLine(te);
Gives us a result of 57
So you need to change
veces = Convert.ToInt32(m[i]);
to
veces = Convert.ToInt32(m[i].ToString());
Hope it helped.
Best regards //KH.
You cannot convert the digits like this. You're overwriting them and taking only the last one. Moreover, you're taking its ASCII code, not digit value. You have to extract all digits first then convert them:
int position = 0;
int veces = 0;
string temp = ""
for (int i = 0; i < m.Length; i++) {
if (Char.IsDigit(m[i]))
position = i;
else
break;
}
veces = Convert.ToInt32(m.SubString(0, i + 1));
Alternatively, you can use regex instead.

Categories

Resources