Just a very small question.
I have a array list named li, where after my conditions I have the contents as:
li[0]="s";
li[1]="a";
li[2]="h";
li[3]="i";
li[4]="4";
Now I wrote the code as:
foreach (string value in li)
{
tb_output.Text = li.ToString();
}
Here, I want that for each list item, the elements should be stored in a string, which I want to display it in a textbox. But i am unable to get "sahil" in tb_output.
Can you tell me where I am wrong. I am unable to take it. I am a beginner, so it is a kind of trouble to me.
If li is a char[], use tb_output.Text = new String(li)
If li is a List<char>, use tb_output.Text = new String(li.ToArray())
If li is a string[] or List<string>, use tb_output.Text = String.Concat(li)
Otherwise, if li contains chars, use tb_output.Text = new String(li.Cast<char>().ToArray())
Otherwise, if li contains string, use tb_output.Text = String.Concat(li.Cast<string>())
You should avoid using ArrayLists whenever possible. Either use List<char> or char[] array. I've used char because you're only holding chars but you can change this to string if you're going to use more than one character.
With a char array, you can simply do this
string myString = new string(li);
Alternatively, you can simply use the String.Concat method and pass in the List or Array.
tb_output.Text = String.Concat(myArrayOrList);
Update for clarification of comment
If you want to use a List<T>, you can do this.
List<char> li = new List<char>() { 's', 'a', 'h', 'i', 'l' };
tb_output.Text = String.Concat(li);
If you really must use an ArrayList here then you can simply convert that ArrayList to an array of chars and use the first method described above (new string(myCharArray))
try
{
tb_output.Text = new string((char[])myArrayList.ToArray(typeof(char)));
}
catch(InvalidCastException ex)
{
//handle any problems with the casting
}
I've added a try..catch block for the ArrayList because if there's an element in the array list that can't be cast to a char then an InvalidCastException is thrown. This isn't generally needed with a List<char> because you know that the list can only have chars in them whereas an ArrayList can have any object type.
Update 2 based on comments
The line new string((char[])myArrayList.ToArray(typeof(char)) can be broken down.
First we are converting the ArrayList to an Array using the the method ToArray()
myArrayList.ToArray();
However, we want to tell the ToArray method to convert every object inside to the ArrayList to a char because, at the moment, the ArrayList is holding object types and not char types. So we pass that information into the method.
myArrayList.ToArray(typeof(char));
We can create a new string from an array of chars by doing
string newString = new string(arrayOfChars);
At the moment we have an Array from the ToArray method but the string constructor here needs an array of chars (char[]) so we cast the Array that we have to a char[] which is why we have
(char[])myArrayList.ToArray(typeof(char));
So we now have a char[] from the original ArrayList and can pass that into the string constructor.
new string((char[])myArrayList.ToArray(typeof(char)));
You still haven't given a reason for why you're using an ArrayList but you'll have to deal with potential performance issues and casting exceptions as you may accidentally put an object into the ArrayList that can't be converted into a char (which is why we have the Try..Catch block).
How about trying
foreach (string value in li)
{
tb_output.Text += value;
}
The other answers should work for your particular question, however, if you want to write to that textbox the contents of li, you should instead do it in this manner.
string word = "";
foreach(string s in li)
{
word += s;
}
tb_output.Text = s;
That way, you clear out the textbox each time you write the array to it.
Better yet, especially if are dealing with a large array, improve performance by using StringBuilder (which you can get by adding "using System.Text;" to the top of your file.
StringBuilder stb = new StringBuilder();
foreach(string s in li)
{
stb.Append(s);
}
tb_output.Text = stb.ToString();
You need to append with +=
foreach (string value in li)
{
tb_output.Text += li.ToString();
}
You can join all elements from an array using String.Join method.
It takes two parameters, the first is: "join with what?", you can join the elements and separate them with a comma for example. The second parameter is your IEnumerable<T>, you can join elements of a List<T> and anything that comes from IEnumerable<T>.
So you could do
tb_output.Text = String.Join("", li);
This will return the string sahi4 as we are joining the array with an empty string.
Or you can use String.Concat already mentioned by keyboardP.
tb_output.Text = String.Concat(li);
Which will concatenate all values.
Alternatively you could build the string using a StringBuilder.
StringBuilder b = new StringBuilder();
foreach (string value in li)
{
sb.Append(value);
}
tb_output.Text = sb.ToString(); // returns the built string
Foreach will return one element at time from your li array and put into value as you named it. Instead of trying to use li.ToString() which will convert the array to a string inside the foreach, you should use value to get the string in each position...
Also, if you are concatenating strings you should use StringBuilder in cases like these, but you could also use the operator +.
stringA = stringA + "B"; // or
stringA += "B";
Related
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.
Since I'm using .NET 1.1, I can't use a generic List of string, as generics were not part of the language yet. So I'm trying to use a StringBuilder, but get this err msg:
"foreach statement cannot operate on variables of type 'System.Text.StringBuilder' because 'System.Text.StringBuilder' does not contain a definition for 'GetEnumerator', or it is inaccessible"
with this code:
public StringBuilder linesToSend;
. . .
foreach (string _line in this.linesToSend)
{
serialPort.Write(_line);
}
Is there something wrong with my code, or is StringBuilder really disallowed from foreach loops? If the latter, is String[] my best recourse?
Old question, I know, but something potentially useful:
If each of your strings were built with .AppendLine or you inserted a new line, you can do
string[] delim = { Environment.NewLine, "\n" }; // "\n" added in case you manually appended a newline
string[] lines = StringBuilder.ToString().Split(delim, StringSplitOptions.None);
foreach(string line in lines){
// Do something
}
A StringBuilder doesn't store the lines that you append. It simply is used to build the final string. Assuming you've added everything to the StringBuilder already, you can do:
// Write the complete string to the serialPort
serialPort.Write(linesToSend.ToString());
This is correct. A StringBuilder is designed to help you build one final output string as the others have stated.
If you have a variable number of strings you need to work on, you can use an ArrayList and iterate over that.
ArrayList strings = new ArrayList();
// populate the list
foreach (string str in strings) {
// do what you need to.
}
If you're afraid that the array list might contain other objects (as it isn't strongly typed) you can cast it safely instead:
foreach (object obj in strings) {
string str = obj as string;
// If null strings aren't allowed, you can use the following
// to skip to the next element.
if (str == null) {
continue;
}
}
A StringBuilder is building just one string, so how could you foreach it to get a whole sequence of strings?
If you need to write line by line, maybe use an ArrayList, add each line string to that, and foreach with string as the foreach variable type (Object will be cast to String). Or even better, use StringCollection (thank to comment by Anthony Pegram, to the original question; I had forgotten this class).
But why not upgrade to a newer version of .NET?
The foreach loop works by calling the GetEnumerator from the interface IEnumerable which will return an enumerator that foreach uses to get the next element of the object.
StringBuilder does not implement IEnumerable or IEnumerable<T> which would allow the foreach to work. You are better off using a string[] or StringCollection in this case and when you are done you can concatenate the collection using a StringBuilder.
ex:
StringBuilder stringBuilder = new StringBuilder();
foreach(string line in array)
{
serialPort.Write(line);
stringBuilder.Append(line);
}
What you're looking for is an array of strings if you know the number of elements, or else a dictionary.
In Java there is a method splitByCharacterType that takes a string, for example 0015j8*(, and split it into "0015","j","8","*","(". Is there a built in function like this in c#? If not how would I go around building a function to do this?
public static IEnumerable<string> SplitByCharacterType(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentNullException(nameof(input));
StringBuilder segment = new StringBuilder();
segment.Append(input[0]);
var current = Char.GetUnicodeCategory(input[0]);
for (int i = 1; i < input.Length; i++)
{
var next = Char.GetUnicodeCategory(input[i]);
if (next == current)
{
segment.Append(input[i]);
}
else
{
yield return segment.ToString();
segment.Clear();
segment.Append(input[i]);
current = next;
}
}
yield return segment.ToString();
}
Usage as follows:
string[] split = SplitByCharacterType("0015j8*(").ToArray();
And the result is "0015","j","8","*","("
I recommend you implement as an extension method.
I don't think that such method exist. You can follow steps as below to create your own utility method:
Create a list to hold split strings
Define strings with all your character types e.g.
string numberString = "0123456789";
string specialChars = "~!##$%^&*(){}|\/?";
string alphaChars = "abcde....XYZ";
Define a variable to hold the temporary string
Define a variable to note the type of chars
Traverse your string, one char at a time, check the type of char by checking the presence of the char in predefined type strings.
If type is new than the previous type(check the type variable value) then add the temporary string(not empty) to the list, assign the new type to type variable and assign the current char to the temp string. If otherwise, then append the char to temporary string.
In the end of traversal, add the temporary string(not empty) to the list
Now your list contains the split strings.
Convert the list to an string array and you are done.
You could maybe use regex class, somthing like below, but you will need to add support for other chars other than numbers and letters.
var chars = Regex.Matches("0015j8*(", #"((?:""[^""\\]*(?:\\.[^""\\]*)*"")|[a-z]|\d+)").Cast<Match>().Select(match => match.Value).ToArray();
Result
0015,J,8
How I set new value for an string by index value?
I tried:
string a = "abc";
a[0] = "A";
not works for strings, but yes for chars. Why?
Strings in C# (and other .NET languages which use System.String in the base class library) are immutable. That is, you can't modify a string character by character that way (or for that matter, can you modify a string ever).
If you want to modify a string based on the index, you have to convert it to an array using System.String.ToCharArray() first. You convert it back to a string using System.String's constructor, passing in the modified array.
Your example would have to be changed to look like:
string a = "abc";
char[] array = a.ToCharArray();
array[0] = 'A'; //Note single quotes, not double quotes
a = new string(array);
The System.String type does not permit writing by index (or via any means -- to change a the content of a String variable, one must replace it with a reference to an entirely new String). The System.Text.StringBuilder type does, however, permit writing by index. One may create a new System.Text.StringBuilder object (optionally passing a string to the constructor), manipulate it, and then use its ToString method to convert it back to a string.
A replacement would be this:
string a = "abc";
a = a.Remove(0, 1);
a = a.Insert(0, "A");
or for the C say:
string a = "abc";
a = a.Remove(2, 1);
a = a.Insert(2, "C");
Also using a stringbuilder may work as per http://msdn.microsoft.com/en-us/library/362314fe.aspx
StringBuilder sb = new StringBuilder("abc");
sb[0] = 'A';
sb[2] = 'C';
string str = sb.ToString();
Use StringBuilder if you need a mutable String.
Also: a[0] can represent one character while "A" is a String object-it is illegal.
a[0] for a character is a address in memory to which you can assign a value.
string on the other hand is a class and in this case the a[0] is actually a function call to the overloaded operator[]. You can't assign values to functions.
I want to pass a string array (separated by commas), then use a function to split the passed array by a comma, and add in a delimiter in place of the comma.
I will show you what I mean in further detail with some broken code:
String FirstData = "1";
String SecondData = "2" ;
String ThirdData = "3" ;
String FourthData = null;
FourthData = AddDelimiter(FirstData,SecondData,ThirdData);
public String AddDelimiter(String[] sData)
{
// foreach ","
String OriginalData = null;
// So, here ... I want to somehow split 'sData' by a ",".
// I know I can use the split function - which I'm having
// some trouble with - but I also believe there is some way
// to use the 'foreach' function? I wish i could put together
// some more code here but I'm a VB6 guy, and the syntax here
// is killing me. Errors everywhere.
return OriginalData;
}
Syntax doesn't matter much here, you need to get to know the Base Class Library. Also, you want to join strings apparently, not split it:
var s = string.Join(",", arrayOFStrings);
Also, if you want to pass n string to a method like that, you need the params keyword:
public string Join( params string[] data) {
return string.Join(",", data);
}
To split:
string[] splitString = sData.Split(new char[] {','});
To join in new delimiter, pass in the array of strings to String.Join:
string colonString = String.Join(":", splitString);
I think you are better off using Replace, since all you want to do is replace one delimiter with another:
string differentDelimiter = sData.Replace(",", ":");
If you have several objects and you want to put them in an array, you can write:
string[] allData = new string[] { FirstData, SecondData, ThirdData };
you can then simply give that to the function:
FourthData = AddDelimiter(allData);
C# has a nice trick, if you add a params keyword to the function definition, you can treat it as if it's a function with any number of parameters:
public String AddDelimiter(params String[] sData) { … }
…
FourthData = AddDelimiter(FirstData, SecondData, ThirdData);
As for the actual implementation, the easiest way is to use string.Join():
public String AddDelimiter(String[] sData)
{
// you can use any other string instead of ":"
return string.Join(":", sData);
}
But if you wanted to build the result yourself (for example if you wanted to learn how to do it), you could do it using string concatenation (oneString + anotherString), or even better, using StringBuilder:
public String AddDelimiter(String[] sData)
{
StringBuilder result = new StringBuilder();
bool first = true;
foreach (string s in sData)
{
if (!first)
result.Append(':');
result.Append(s);
first = false;
}
return result.ToString();
}
One version of the Split function takes an array of characters. Here is an example:
string splitstuff = string.Split(sData[0],new char [] {','});
If you don't need to perform any processing on the parts in between and just need to replace the delimiter, you could easily do so with the Replace method on the String class:
string newlyDelimited = oldString.Replace(',', ':');
For large strings, this will give you better performance, as you won't have to do a full pass through the string to break it apart and then do a pass through the parts to join them back together.
However, if you need to work with the individual parts (to recompose them into another form that does not resemble a simple replacement of the delimiter), then you would use the Split method on the String class to get an array of the delimited items and then plug those into the format you wish.
Of course, this means you have to have some sort of explicit knowledge about what each part of the delimited string means.