How do you swap character in an array in C#? [duplicate] - c#

This question already has answers here:
Is there an easy way to change a char in a string in C#?
(8 answers)
Replacing a char at a given index in string? [duplicate]
(7 answers)
how do I set a character at an index in a string in c#?
(7 answers)
Closed 5 years ago.
for (int i = 0; i < s.Length -1; i++)
{
temp = s[i]; // no errors here
s[i] = s[j]; //Property or indexer string.this[int] cannot be assigned to -- it is read only
s[j] = temp; //Property or indexer string.this[int] cannot be assigned to -- it is read only
}
I am dumb so please explain to me as if I was an 8 year old. Is this something you cannot do in C#? How do I fix this?

As others have already suggested s seems a string and thay are immutable so you have to convert s to a char array to do that. A possible way to do it would be:
char[] array = s.ToCharArray();
char temp = array[i];
array[i] = array[j];
array[j] = temp;
s = new string(array);

Related

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

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());
}

What Is this C# Code doing in algorithms? [duplicate]

This question already has answers here:
Ternary Operator in C#
(4 answers)
Closed 2 years ago.
encoded Data = (encoded Data | bit Shift Buffer)
This line:
j = j + 1 == key.Length ? 0 : j + 1;
could also be written as:
if ((j+1) == key.Length)
j = 0;
else
j = j+1;

C# System.IndexOutOfRangeException or cant convert to Long [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I'm kinda of having this error:
"System.IndexOutOfRangeException: Index was out of the Array"
When I change int=1 to long=1 it says it can't convert long to int.
I'm trying to save all output of N into the Array and show at the end what is saved into arrays.
static void Main(string[] args)
{
int a = 0;
a = Convert.ToInt64(Console.ReadLine());
int[] array = new int[a];
if (a == 0)
{
Console.WriteLine("Falsche eingabe.");
}
else
{
long n = 1;
for (int i = 1; i <= array.Length; i++)
{
n *= i;
array[i] = n;
Console.WriteLine("N: " + i + " Fakultät von N: " + array[i]);
}
}
Console.ReadKey();
}
Indexes of arrays begin from 0 not from one. Therefore in your for loop, i <= array.Length, when i is equal to the length you enter and try array[array.Length] which throws the exception. Change to:
for (int i = 0; i < array.Length; i++)
Reason indexes are zero based is that the language is based on C where an array is a pointer to the location that was allocated for the array:
int *arrayPointer;
And then to go through the array one needs to go to arrayPointer + sizeof(int)*i. So for the first position of the array i should start from zero
In addition this line doesn't compile:
a = Convert.ToInt64(Console.ReadLine());
a is of type int while you are converting to long. Use ToInt32

I have a loop on C# in array but it does not work as well [duplicate]

This question already has answers here:
How to get the length of row/column of multidimensional array in C#?
(5 answers)
Closed 5 years ago.
this is the error that I get now:
for(int i = 0; i < arrDate.Length; i++)
{
Console.WriteLine(arrDate[i, 0]);
}
the error message is:Index out of range exception was unhandled.
this is the array:
string[,] arrDate = new string[2, 3];
arrDate[0, 0] = "10/05/2017";
arrDate[0, 1] = "15/05/2017";
arrDate[0, 2] = "mily";
arrDate[1, 0] = "20/05/2017";
arrDate[1, 1] = "22/05/2017";
arrDate[1, 2] = "many";
this question is different from this question
The Length property of a multidimensional array gives the total amount of elements. Imagine you have a two dimensional 2 x 3, then length returns 2 x 3 = 6.
You code tries to iterate about 6 rows (in this example) and would raise an exception while trying to access the third row (i = 2).
Please try
for(int i = 0; i < arrDate.GetLength(0); i++)
{
Console.WriteLine(arrDate[i, 0]);
}
GetLength(0) returns the length of the first dimension.

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();

Categories

Resources