This question already has answers here:
Splitting a string / number every Nth Character / Number?
(17 answers)
Closed 8 years ago.
I have a string that looks something like:
0122031203
I want to be able to parse it and add the following into a list:
01
22
03
12
03
So, I need to get each 2 characters and extract them.
I tried this:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i=i+2) {
mList.Add(_CAUSE.Substring(i, _CAUSE.Length));
}
return mList;
but something is not right here, I keep getting the following:
Index and length must refer to a location within the string. Parameter
name: length
Did I get this wrong?
How about using Linq?
string s = "0122031203";
int i = 0;
var mList = s.GroupBy(_ => i++ / 2).Select(g => String.Join("", g)).ToList();
I believe you have may have specified the length incorrectly in the Substring function.
Try the following:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i = i + 2)
{
mList.Add(_CAUSE.Substring(i, 2));
}
return mList;
The length should be 2 if you wish to split this into chunks of 2 characters each.
when you do the substring, try _CAUSE.SubString(i, 2).
2points:
1) as previously mentioned, it should be substring(i,2);
2) U should consider the case when the length of ur string is odd. For example 01234: do u want it 01 23 and u'll discard the 4 or do u want it to be 01 23 4 ??
Related
This question already has answers here:
Read numbers from the console given in a single line, separated by a space
(7 answers)
Split string, convert ToList<int>() in one line
(11 answers)
Closed 3 years ago.
I have gone through this solution. But this is not solving my problem. Let's say I have a string:
var aString = "0 -1 12 456 -512";
I want to convert this string to an int array like:
var convertedArray = [0, -1, 12, 456, -512];
How should I approach to solve this problem?
You can simply do this:
var stringNumbers = aString.Split(' ');
var numbers = new int[stringNumbers.Length];
for (int i = 0; i < stringNumbers.Length; i++)
numbers[i] = Convert.ToInt32(stringNumbers[i]);
var convertedArray = Array.ConvertAll(aString.Split(' '), int.Parse);
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I'm new to C# and writing a text moving cipher program. However, when trying to set an array value to a value from another array (plus 3) i always get an IndexOutOfRangeException. That might sound confusing but honestly I have no clue how to really word this.
Removing the +3 didn't help, and it seems trying to set the array from another array always results in the error.
for (int i = 0; i < CipherLength; i++)
{
if (Alphabet.Contains(CipherArray[i]))
{
Console.WriteLine(i);
Console.WriteLine(CipherArray[i]);
CipherArray[i] = Alphabet[CipherArray[i + 3]];
}
else
{
CipherArray[i] = ' ';
}
}
Essentially, i'm trying to set the CipherArray value, in this case the character, to be that character moved by 3, which is what the alphabet array is for.
Expected: If CipherArray[i] = A, then after that it should equal D
Actual:
System.IndexOutOfRangeException: 'Index was outside the bounds of the
array.'
(In all cases)
This is because you are trying to access i + 3 element of CipgerArray, when i points to last element in an array, i + 3 is out of bounds.
Also you are complicating this. Generally characters are represented by ints:
var ch = 'a';
var i = (int)ch;
// i = 97
ch = 'z';
i = (int)ch;
// i = 122
So range is 26 characters. If you want to move every characters by 3, then you need to apply mod function, represented in C# by % operator (if you want to move from z, you need to get a c).
Putting it all together you can write your algorithm like this:
var offset = 3;
var toCipher = "abxz";
toCipher = new string(toCipher
.Select(ch => ((ch - 97) + offset) % 26 + 97)
.Select(ch => (char)ch).ToArray());
Note that I didn't take into account uppercase letters.
The problem is that when you get the
Alphabet[CipherArray[i + 3]]
you are passing it to the alphabet. I'm presuming that the cipher array has letters in it so passing it in the Alphabet will result in an error. What you need to do is say:
Alphabet[i + 3]
That's how I understood the problem. But that, of course, wouldn't fix it, what you really need to do is get the index of the letter in the Alphabet Array then add 3 to it. So:
Alphabet[Arrays.IndexOf(Alphabet, CipherArray[i]) + 3]
You will need to add in the alphabet array after the letter Z, A, B and C once more to compensate for the plus 3. If I did something wrong or didn't understand the problem tell me. Hope it helps.
So as I said in the tittle, I have the string, which contains numbers.
For example ("8 3 -5 42 -1 0 0 -9 4 7 4 -4").
And I know I have to use Int32.Parse and Select method to convert it.
I searched several topics(however only like one or two were in C#) that could be helpfull to me. Technically I found the solution - stringArray.Select(x => Int32.Parse(x)).ToList(); - but I don't understand how to implement it. When I don't change the arguments and only replace "stringArray" with the name of the given string, I am getting an error "error CS1502: The best overloaded method match for 'int.Parse(string, System.Globalization.NumberStyles)' has some invalid arguments
I haven't found anyone with similiar problem, and I have no idea how to solve this(have been dealing with this for few hours now)
When you have a string like
string s = "8 3 -5 42 -1 0 0 -9 4 7 4 -4";
You have to split in in an array with
var arrayOfStrings = s.Split(' '); // Space is the seprator here
And after that, you can convert them to int values with
var intList = new List<int>();
foraech (var _int in arrayOfStrings)
{
intList.Add(Int.Parse(_int));
}
or in a more secure way
var intList = new List<int>();
foraech (var _int in arrayOfStrings)
{
int temp = 0;
if(Int.TryParse(_int, out temp))
{
intList.Add(temp);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to C# so please be gentle. I am using c# in a transformation script and I need to find the 6th highest value in a list such as this
57
50
90
60
57
93
100
53
73
87
77
I can change it into a string array by using
string [] arr = args.Content.Split("\r\n".ToCharArray());
but I get lost from there
Thanks
Paul Fone
If you want to sort it numerically you have to convert the strings to int first, then you can use Enumerable.OrderByDescending and Enumerable.Skip(5).Take(1):
IEnumerable<int> ints = arr.Select(int.Parse)
.OrderByDescending(i => i)
.Skip(5).Take(1);
Console.Write("Sixth element is: " + ints.First());
or create a new list from the ordered sequence at then use Enumerable.ElementAt:
List<int> ints = arr.Select(int.Parse).OrderByDescending(i => i).ToList();
Console.Write("Sixth element is: " + ints.ElementAt(5));
(omitted exception handling for invalid format or too little items)
You can use LINQ, like this:
var res = args.Content.Split("\r\n".ToCharArray())
.Select(int.Parse)
.OrderBy(x=>x)
.Skip(5)
.FirstOrDefault();
To start, you need to first convert your numbers into an int[]. You can do that like this:
string[] strs = args.Content.Split("\r\n".ToCharArray());
int[] ints = new int[strs.Length];
for (int i = 0; i < strs.Length; i++)
ints[i] = int.Parse(strs[i]);
Then you can use Array.Sort(ints); to actually sort them. Then, you use int result = ints[ints.Length - 6 - 1]; to get the sixth-to-last element in the sorted array: that is, the 6th highest element.
The completed code looks like this:
string[] strs = args.Content.Split("\r\n".ToCharArray());
int[] ints = new int[strs.Length];
for (int i = 0; i < strs.Length; i++)
ints[i] = int.Parse(strs[i]);
Array.Sort(ints);
int result = ints[ints.Length - 6 - 1];
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.
Say I have 12345.
I'd like individual items for each number. A String would do or even an individual number.
Does the .Split method have an overload for this?
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.
The fastest way to get what you want is probably the ToCharArray() method of a String:
var myString = "12345";
var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}
You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:
byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();
A little more performant if you're using ASCII/Unicode strings:
byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();
That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5