I have a problem in my code and I have no idea how to fix it. I need to copy every letter of the user entered word to array, but there is an error "Index was outside the bounds of the array". I know that thir error means that I don't have correct size of the array, but I am using ReadLine and I can't enter static size. It can be changed due user entered text.
Code:
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[] { };
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You should define length of str
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[text.Length];//<-- NOTE THIS
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You can use Linq to make this a one-liner:
using System.Linq;
// ...
// ...
var separateLettersAsList = text.ToList();
var separateLettersAsArray = text.ToArray();
Related
My front-end application sends strings that look like this:
"12-15"
to a back-end C# application.
Can someone give me some pointers as to how I could extract the two numbers into two variables. Note the format is always the same with two numbers and a hyphen between them.
string stringToSplit = "12-15";
string[] splitStringArray;
splitStringArray = stringToSplit.Split('-');
splitStringArray[0] will be 12
splitStringArray[1] will be 15
Split the string into parts:
string s = "12-15";
string[] num = s.Split('-');
int part1 = Convert.ToInt32(num[0]);
int part2 = Convert.ToInt32(num[1]);
int[] numbers = "12-15".Split('-')
.Select(x => {
int n;
int.TryParse(x, out n);
return n;
})
.ToArray();
We call Split on a string instance. This program splits on a single character
string s ="12-15";
string[] words = s.Split('-');
foreach (string word in words)
{
int convertedvalue = Convert.ToInt32(word );
Console.WriteLine(word);
}
string[] ss= s.Split('-');
int x = Convert.ToInt32(ss[0]);
int y = Convert.ToInt32(ss[1]);
more info
You can use the below code to split and it will return string for each value, then you can typecast it to any type you wish to ...
string myString = "12-15-18-20-25-60";
string[] splittedStrings = myString.Split('-');
foreach (var splittedString in splittedStrings)
{
Console.WriteLine(splittedString + "\n");
}
Console.ReadLine();
Here is the correct version without the wrong code
string textReceived = "12-15";
string[] numbers = textReceived.Split('-');
List<int> numberCollection = new List<int>();
foreach (var item in numbers)
{
numberCollection.Add(Convert.ToInt32(item));
}
String numberString = "12-15" ;
string[] arr = numberString.Split("-");
Now you will get a string array , you can use parsing to get the numbers alone
int firstNumber = Convert.ToInt32(arr[0]);
Helpful answer related to parsing :
https://stackoverflow.com/a/199484/5395773
You could convert that string explicitly to an integer array using Array.ConvertAll method and access the numbers using their index, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = Array.ConvertAll(number.Split('-'), int.Parse);
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[1]);
}
}
}
Or you can explicitly convert the numeric string using int.Parse method, the int keyword is an alias name for System.Int32 and it is preffered over the complete system type name System.Int32, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = number.Split('-');
var one = int.Parse(numbers[0]);
var two = int.Parse(numbers[1]);
Console.WriteLine(one);
Console.WriteLine(two);
}
}
}
Additional read: Please check int.Parse vs. Convert.Int32 vs. int.TryParse for more insight on parsing the input to integer
string str = null;
string[] strArr = null;
int count = 0;
str = "12-15";
char[] splitchar = { '-' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
MessageBox.Show(strArr[count]);
}
I've been creating a code breaking software and I need to convert the characters from a text file into ascii numbers to allow the shift. I have left my code below but could someone explain how I could do this?
using System;
using System.IO;
namespace CipherDecoder
{
class Program
{
static void Main(string[] args)
{
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
string cipherText = File.ReadAllText(fileText);
string output = #"C:\\Users\Samuel\Documents\Computer_Science\PaDS\output.txt\";
char[] cipherChars = new char[691];
int j = 0;
foreach (char s in cipherText)
{
cipherChars[j] = s;
j++;
}
for(int i = 0; i < cipherChars.Length; i++)
{
cipherChars[i] = cipherChars[i];
}
}
}
}
To get the int values into an int array you could just do this with as a LINQ select. For example:
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
int [] charactersAsInts = File.ReadAllText(fileText).Select(chr => (int)chr).ToArray();
You can,
var asciiNumbersArray = cipherText.Cast<int>().ToArray();
If you cast a char to int you get the ascii number in decimal system.
This is What that I have Tried.Please Suggest me How to convert Assci code into character.
class Decryption
{
static void Main()
{
string file = #"C:\Users\Me\OneDrive\CSharpProgramming\CipherText.txt";
string text = File.ReadAllText(file);
// displaying the contents of the file being read from...
Console.WriteLine(" Encrypted Text: \n\n{0}", text);
foreach (char c in text)
{
int ASCIIValues = (char)c - 4;
Console.Write(ASCIIValues);
}
Console.ReadLine();
Do you want this
int ascii = 50;
char b = (char)ascii;
try this
int[] arr;
for(i<n)
{
string p += (char)arr[i]+4;
}
I'm trying to take a string and split it. However, whenever I use fullName.Split Visual Studio says System.Array does not contain a definition for Split.
This is my main method so far.
public static void Main(string[] args)
{
string inValue;
int noNames;
string[] names = new string[100];
// find number of names
Console.WriteLine("Enter the number of names: ");
inValue = Console.ReadLine();
int.TryParse(inValue, out noNames);
string[] fullName = new string[noNames];
for (int i = 0; i < fullName.Length; i++)
{
string[] name = fullName.Split(' '); //error appears here
}
}
What's strange is that I was able to write another program shortly before this that uses the Split method. That program had no issues. I'm not sure if there is something wrong with my code, or an error with Visual Studio. Can anyone assist me in solving this error? The program isn't complete, if that matters.
You need to call it on the element of the array, not the array itself.. So it would be:
string[] name = fullName[i].Split(' ');
You are trying to split an array, not a string. Arrays cannot be split this way using a certain character like strings
try this
public static void Main(string[] args)
{
string inValue;
int noNames;
string[] names = new string[100];
// find number of names
Console.WriteLine("Enter the number of names: ");
inValue = Console.ReadLine();
int.TryParse(inValue, out noNames);
string[] fullName = new string[noNames];
for (int i = 0; i < fullName.Length; i++)
{
string[] name = fullName[i].Split(' '); //error appears here
}
}
This is a question I have come across and failed
Suppose say
string str = "wordcounter";
One can easily find the Length using str.Length
However, is it possible in C# to get the number of letters, without using any inbuilt functions like Length, SubStr etc
you could write a loop and increment a counter inside this loop:
int numberOfLetters = 0;
foreach (var c in str)
{
numberOfLetters++;
}
// at this stage numberOfLetters will contain the number of letters
// that the string contains
there is also another way:
int numberOfLetters = str.ToCharArray().Length;
there is also another, even crazier way using the SysStringByteLen function which operates on a BSTR. Strings in .NET are layed out in memory by using a 4 byte integer containing the length of the string followed by that many 2 byte UTF-16 characters representing each character. This is similar to how BSTRs are stored. So:
class Program
{
[DllImport("oleaut32.dll")]
static extern uint SysStringByteLen(IntPtr bstr);
static void Main()
{
string str = "wordcounter";
var bstr = Marshal.StringToBSTR(str);
// divide by 2 because the SysStringByteLen function returns
// number of bytes and each character takes 2 bytes (UTF-16)
var numberOfLetters = SysStringByteLen(bstr) / 2;
Console.WriteLine(numberOfLetters);
}
}
Obviously doing something like this instead of using the built-in Length function should never be done in any real production code and the code shown here should not be taken seriously.
My answer is bit late, but I would like to post the same. Though all above mentioned solutions are correct, but I believe that the IL of the foreach does knows about the length of the iterable before iterating it. Talking of a pure solution, here's mine:
private int stringLength(string str) {
int length = 0;
bool done = false;
do {
try {
char c = str[length];
length++;
} catch (IndexOutOfRangeException) {
done = true;
}
} while(!done);
return length;
}
How about?
int myOwnGetStringLength(String str)
{
int count = 0;
foreach(Char c in str)
count++;
return count;
}
not very fast but yo can always loop and count the number of caracter contained.
int counter = 0;
foreach (var caracter in str)
{
counter ++;
}
class Program
{
static void Main(string[] args)
{
string Name = "He is palying in a ground.";
char[] characters = Name.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i = Name.Length - 1; i >= 0; --i)
{
sb.Append(characters[i]);
}
Console.Write(sb.ToString());
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a string to find its lenght");
string ch = Console.ReadLine();
Program p = new Program();
int answer = p.run(ch);
Console.WriteLine(answer);
Console.ReadKey();
}
public int run(string ch)
{
int count = 0;
foreach (char c in ch)
{
count++;
}
return count;
}
}
My general solution involves without using 'foreach' or 'StringBuilder' (which are C# specific) or without catching any exception.
string str = "wordcounter";
str += '\0';
int x = 0;
while (str[x] != '\0')
x++;
Console.WriteLine(x); //Outputs 11
class Program
{
static void Main(string[] args)
{
string test = "test";
//string as char array:
//iterate through char collection
foreach (char c in test)
{
//do something
}
//access elements by index
Console.WriteLine("Contents of char array : {0}, {1}, {2}, {3}", test[0], test[1], test[2], test[3]);
Console.ReadKey();
}
}
namespace ConsoleApplication {
class Program {
static void Main(string[] args) {
string testString = "testing";
int x = 0;
foreach(char c in testString) {
x++;
}
Console.WriteLine("\nLength Of String:{0}", (x));
Console.Read();
}
}