How to convert char[] to char? - c#

I am new to C#. I am trying to declare a char array that contains few string values. Trying to use the ToCharArray() method to copy the string to a char array it return character array of a string. However, I get the error saying it cannot implicitly convert char[] to char.
Here's the code I have written:
char[] country= new char[5];
country[1] = "japan".ToCharArray();
country[2] = "korea".ToCharArray();
It works when I write it like this:
char[] country= "japan".ToCharArray();
but I want to use it in an array so I can randomize and choose an element from any of 5 values assigned. I would really appreciate if anyone could help, thanks.

I believe you try to have array of char arrays:
char[][] countries = new char[5][];
countries[1] = "japan".ToCharArray();
countries[2] = "korea".ToCharArray();

Every element in the array is one character.
So country[0] is "j", country[1] is "a" and so on.
with
country[1] = "japan".ToCharArray();
you try to put an array into a char, and give you an error.
Perhaps you want a list of chars. So you can use an array of array or a list of country.
for the first country for example
List<string> country = new List<string>() {
"japan",
"korea"
};
var random = new Random();
var character = country[0][random.Next(0, country[0].Length)];

Related

Converting string array to char array

I want to read .txt file, extract every distinct from it and save it to array. So far I came up with this:
string text = File.ReadAllText(#"C:\Users\ASUS\Desktop\szyfrowanie\TextSample.txt");
string uniqueLetters = new string(text.Distinct().ToArray());
I couldn't find any way to save those distinct letters to a char array. Now I want to convert the uniqueLetters array to a char array. I've been trying through certain things like creating a new char[] array and assigning uniqueLetter value in a for loop. ToCharArray() also failed me. Does anybody have any ideas how to do it?
The ToArray method returns a char[], that is, a char array. Use it like this in your code:
string text = File.ReadAllText(#"C:\Users\ASUS\Desktop\szyfrowanie\TextSample.txt");
char[] uniqueLetters = text.Distinct().ToArray();
The return value type is char array and not string.
string text = "AABBCC";
var uniqueLetters = text.Distinct().ToArray();
Output (array of chars):
A, B, C.
Edit:
Dont forget:
using System.Linq;

How to store text from a file-list into a variable in c#

Hi I am new to programming. I would like to read a text file and take the values ( strings ) and store each character of the string in an array individually. I have used a list to take in the vales from the text file. I am finding it difficult to move them into an array and then use those values in my program. Please find me a solution if possible. Thanking you in advance.
public class file_IO
{
string[] letters = new string[] //I would like to store it in this variable
public void File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
foreach (string line in file_lines)
{
}
}
}
Hope this will work for you!.
public char[] File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
StreamReader sr = new StreamReader(filepath);
string fileContentInString = sr.ReadToEnd();
sr.Close();
return fileContentInString.ToCharArray();
}
List<List<char>> linesAsChars = File.ReadAllLines(filepath)
.Select(l => l.ToList())
.ToList();
This will get a List of List of chars.
string implements IEnumerable<char>, so with ToList each line in the file is translated to List<char>.
Solution to "store each character of the string in an array individually" is fairly easy because string is in fact an array of char. You can do this using something like this :
char[] letters;
public void File_Reader()
{
string filepath = #"env.txt";
letters = File.ReadAllText(filePath).ToArray();
}
I'm not really sure if I have understood your question properly, but from what I have read, I will assume that you want an array of lines (which are strings).
In this case, you don't need to do much as the File.ReadAllLines() method naturally outputs an array of string variables.
Remove the for loop and replace
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
with:
letters = File.ReadAllLines(filepath)
In case what you want is actually an array of every char value in your file, I would refer to #m.rogalski's answer and declare an array of char[], for example, declare:
char[] fileChars;
and then replace the line I mentioned earlier with:
fileChars = readAllText(filePath).toCharArray()
You will notice that you do not need a loop in either of the above situations. Hope I helped.

Is there a way to access the character of a string in a string array in C#?

I have a string array, I want to access the characters of the first element in that array:
string[] str= new string[num];
for(int i = 0; i < num; i++)
{
str[i] = Console.ReadLine();
}
To access the characters of the first element in the string array, in Java
str[0].CharAt[0] // 1st character
Is there a way in C# for this? The only function I could see was use of substring. It will incur more overhead in such case.
You would use:
str[0][0]
where the first [0] is accessing the 0th array member, while the next [0] is the indexer defined by System.String which gives the 0th char value (UTF-16 code unit) of the string.
Yes, you can do that:
string[] s = new string[]{"something", "somethingMore"};
char c = s[0][0];
You could convert the first string of the string array to a character array and simply get the first value of the character array.
string[] stringArray = {"abc"};
char[] charArray = stringArray[0].ToCharArray();
char first = charArray[0];

Why is this considered going from string[] to int[]?

It keeps giving me an error message here and I don't understand why.
int[] user31 = new int[53];
user31 = System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray();
Because ReadLines returns strings, you know. It is right there in the documentation:
http://msdn.microsoft.com/en-us/library/dd383503(v=vs.110).aspx
and you just do "TOArray".
If you would parse the rows before doing ToArray....
Skip(1675).Take53.Select (x=> Int.Parse(x)).ToArray()
(or along this line)
You would get an array of ints, but calling ToArray on an enum of string returns an array of strings.
Just look at the return type of System.IO.File.ReadLines methods. It is String[].
You call Skip and Take as a result you will have an IEnumerable<String> calling ToArray again will give you a String[] not int[].
Because each line of a text file is just that, text. If you can guarantee that each line is actually an integer, you can do something like this:
int[] user31 = new int[53];
string[] lines = System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray();
int i = 0;
foreach (var line in lines)
{
user31[i++] = Convert.ToInt32(lines[i]);
}
ReadLines returns strings with an array
I assume that your ratings.txt file contain int values in each line
you need to convert string array to int array ..
int[] user31 = new int[53];
user31= System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray().Select(n => Convert.ToInt32(n)).ToArray();
This is because the user31 is an integer array but ReadLine returns string[].
Try like this:
List<string> str =new List<string>(new string[] {"123", "234","345","456","678","678","890"});
List<int> a = str.Skip(1675).Take(53).ConvertAll(new Converter<string, int>(int.Parse));
No need to explicitly parse it yourself and return an array. ConvertAllwill do the job to return an array.
EDIT:
Included a running test case using ConvertAll function.

Length of array created by using split string

I know that we can use string.split() to put our data into arrays like below:
string[] strSplit = Data.Split('|');
But can we know how many array items it created? I need that number.
It will create a single array of multiple strings. Like T.S. commented, you can get the number of strings using the length property of the returned array
int length = strSplit.length
Sometime you need remove the empty entries in spilt result:
string[] strSplit = data.Split(new []{"|"}, StringSplitOptions.RemoveEmptyEntries);
And get the length like this:
int length = strSplit.Length;

Categories