How can I get array or array values from for-loop?
Example first outputs prints right solution, but second output prints just last line, last word of array.
How to get correct value for array from splitLine and save it in variable for using it later?
File text
Title:
Here is my first line.
Here is my second line.
Here is my third line.
Here is my fourth line.
Here is my fifth line.
Code
using System;
using System.IO;
namespace Array
{
class Class
{
private static void Main()
{
string[] lines = File.ReadAllLines(
#"file.txt");
string[] array = new string[] {};
for (int i = 0; i < lines.Length; i++)
{
string[] splitLine = lines[i].Split();
for (int j = 0; j < splitLine.Length; j++)
{
Console.WriteLine(splitLine[j]);
array = splitLine[j].Split();
}
}
Array.ForEach(array, Console.WriteLine);
}
}
}
If you are expecting the 'array' variable to accumulated values from each string split operations, then you don't have it quite right. As written your code only sets the 'array' variable to the last string split operations. You should consider using a collection type like List as the type for your array. Then call the Add method to add a single item or the AddRange method to add an enumeration (which can be an array).
The ReadAllLines() method is already splitting your text into lines. I'm not clear if you want to split it further? If not, simply:
var lines = File.ReadAllLines(#"file.txt");
lines.ToList().ForEach(Console.WriteLine);
Should output the lines to the console
Related
In my C# program, I'm trying to read in data from a text file to an array. I've looked at many answers on here and can't figure out what's wrong with my code. Whenever I run it, I get an exception that says that I got an unhandled exception of type 'System.IndexOutOfRangeException', but I don't understand why the index would be out of range.
Here's what I have:
string[] namesArray = new string[] { };
using (var sr = new StreamReader(mydocpath + #"\nameIDLines.txt"))
{
for (int i = 1; i < numLines; i++)
{
nameIDLine = sr.ReadLine();
nameIDLine = nameIDLine.Split(new string[] { "ID" }, StringSplitOptions.None)[0];
namesArray[i] = nameIDLine;
}
}
When you do this:
string[] namesArray = new string[] { };
You're initializing an array with length 0. Therefore, when you do namesArray[i], it will always be out of range regardless of i.
Since you know the number of lines, and therefore the number of items, you can initialize the array with that number:
string[] namesArray = new string[numLines];
As #stybl pointed out, the problem is that you are initializing a zero-length array to store your lines... and that will always lead to an "index out of range" exception. On the top of that, I wonder how you are managing to get a consistent numLines value while using a StreamReader to parse the file... this is very risky since you must be sure that the file always contains enough lines.
I suggest you to use the following approach instead:
String[] lines = File.ReadAllLines(mydocpath + #"\nameIDLines.txt");
If you want to take a specific number of lines from the file, you can proceed as follows:
String[] lines = File.ReadAllLines(mydocpath + #"\nameIDLines.txt").Take(numLines).ToArray();
This question already has answers here:
Is there an easy way to change a char in a string in C#?
(8 answers)
Closed 5 years ago.
This is kind of a basic question, but I learned programming in C++ and am just transitioning to C#, so my ignorance of the C# methods are getting in my way.
A client has given me a few fixed length files and they want the 484th character of every odd numbered record, skipping the first one (3, 5, 7, etc...) changed from a space to a 0. In my mind, I should be able to do something like the below:
static void Main(string[] args)
{
List<string> allLines = System.IO.File.ReadAllLines(#"C:\...").ToList();
foreach(string line in allLines)
{
//odd numbered logic here
line[483] = '0';
}
...
//write to new file
}
However, the property or indexer cannot be assigned to because it is read only. All my reading says that I have not set a setter for the variable, and I have tried what was shown at this SO article, but I am doing something wrong every time. Should what is shown in that article work? Should I do something else?
You cannot modify C# strings directly, because they are immutable. You can convert strings to char[], modify it, then make a string again, and write it to file:
File.WriteAllLines(
#"c:\newfile.txt"
, File.ReadAllLines(#"C:\...").Select((s, index) => {
if (index % 2 = 0) {
return s; // Even strings do not change
}
var chars = s.ToCharArray();
chars[483] = '0';
return new string(chars);
})
);
Since strings are immutable, you can't modify a single character by treating it as a char[] and then modify a character at a specific index. However, you can "modify" it by assigning it to a new string.
We can use the Substring() method to return any part of the original string. Combining this with some concatenation, we can take the first part of the string (up to the character you want to replace), add the new character, and then add the rest of the original string.
Also, since we can't directly modify the items in a collection being iterated over in a foreach loop, we can switch your loop to a for loop instead. Now we can access each line by index, and can modify them on the fly:
for(int i = 0; i < allLines.Length; i++)
{
if (allLines[i].Length > 483)
{
allLines[i] = allLines[i].Substring(0, 483) + "0" + allLines[i].Substring(484);
}
}
It's possible that, depending on how many lines you're processing and how many in-line concatenations you end up doing, there is some chance that using a StringBuilder instead of concatenation will perform better. Here is an alternate way to do this using a StringBuilder. I'll leave the perf measuring to you...
var sb = new StringBuilder();
for (int i = 0; i < allLines.Length; i++)
{
if (allLines[i].Length > 483)
{
sb.Clear();
sb.Append(allLines[i].Substring(0, 483));
sb.Append("0");
sb.Append(allLines[i].Substring(484));
allLines[i] = sb.ToString();
}
}
The first item after the foreach (string line in this case) is a local variable that has no scope outside the loop - that’s why you can’t assign a value to it. Try using a regular for loop instead.
Purpose of for each is meant to iterate over a container. It's read only in nature. You should use regular for loop. It will work.
static void Main(string[] args)
{
List<string> allLines = System.IO.File.ReadAllLines(#"C:\...").ToList();
for (int i=0;i<=allLines.Length;++i)
{
if (allLines[i].Length > 483)
{
allLines[i] = allLines[i].Substring(0, 483) + "0";
}
}
...
//write to new file
}
Is this the best way to set each item of a string array to that of an Enumerable array? I came up with this approach on my own, I tried to use my google-foo but couldn't really come up with coherent sentences to describe what i'm trying to do here..
string[] adapterDesc = new string[] {};
int i = 0;
foreach(NetworkInterface adapter in adapters)
{
adapterDesc[i] = adapter.Description;
i++;
}
...
No, that code will fail with an IndexOutOfRange exception because you have declared an array of strings that could contain zero elements.
So when you try to set the first element it will crash.
Instead you could use a List where you can add elements dynamically
List<string> adapterDesc = new List<string>();
foreach(NetworkInterface adapter in adapters)
{
adapterDesc.Add(adapter.Description);
}
...
A List is more flexible than an array because you don't have to know before the size of the array and you could still use it like it was an array
for(int x = 0; x < adapterDesc; x++)
{
Console.WriteLine(adapterDesc[x]);
}
If you want to use Linq then you could even reduce your code to a single line with
string[] adapterDesc = NetworkInterface.GetAllNetworkInterfaces()
.Select(ni => ni.Description)
.ToArray();
This code takes an array of char as parameter and return an array that contains each word of the array. No word can contain spaces. Might need some help as I get an error on tab[i][j] = str[counter], but I think you can tell what I want it to do.
public static char[][] split_string(char[] str)
{
char[][] tab = new char[20][];
int x = 1;
int counter = 0;
for (int i = 0; i < str.Length; i++)
{
for (int j = 0; j < str.Length; j++)
{
if (str[i] != ' ')
{
tab[i][j] = str[counter];
}
else
{
counter++;
break;
}
counter++;
}
}
return tab;
}
The immediate problem
When you declare char[][] tab = new char[20][];
you are creating an array of arrays of char, of size 20. That is an array that has 20 elements that are arrays of char, each one of those 20 arrays will be set to null.
So, when you try to do tab[i][j] = str[counter]; you are trying to set the element on the index 'j´ of the array on the index 'i' of the array tabs, but the array on the index 'i' of the array 'tabs' is null (as all the other arrays in the array 'tabs' are). So you get a NullReferenceException.
In general, if you get a NullReferenceException it means that some reference is null, duh. It probably means you forgot to initilize something... You wil be pointed to where it happened, and it would be your work to figure out what was null there, why is it null, question yourself if it is right that it is null... if it is not, then fix it by intializing the variable. If it is, then check for null and do the appropiate thing for that case.
In your particular case, it shouldn't be null. So you have to initilize it. Initialize what? The array that you will be filling. Remember that when you said new char[20][]; you created an array of 20 arrays that are set to be null, but you don't want them to be null, but arrays.
So a simple tab[i] = new char[str.Length]; befor the inner loop will solve the immediate problem.
The other problem
Ok, but you will face another problem once that one is fixed. You see, you are creating an array of 20 elements. But the array you get on the parameter str maybe longer. So - when that happens - you will get an IndexOutOfRangeException as you try to write beyond the element of index 19 of your array.
And honestly... It is hard to infer from the code what you are trying to do.
What you are trying to do
Guessing from the signature of the method, I guess you want to take an array of chars and return and array of arrays of chars, where wach array contains a word.
And for some mysterious reasons you are not using string. If I'm right, the method that you should be using is string.Split.
These are my guesses for the mysterious reasons:
You are victim of a sadict teacher that wants you to not use string, List or anything like that.
You need to do interop with some system that only understand arrays of chars.
You used the wrong language tag, and this is a C question instead of a C# one.
Ok, let's assume it is the interop case. You can do this:
1) Create a new array from the char array:
new string(str)
2) Call split on it:
(new string(str)).Split(' ')
3) Convert each returned string into a char array:
from string s in (new string(str)).Split(' ') select s.ToCharArray()
4) Conver the resulting collection to an array:
(from string s in (new string(str)).Split(' ') select s.ToCharArray()).ToArray();
5) wrap it on a method:
public static char[][] split_string(char[] str)
{
return (from string s in (new string(str)).Split(' ') select s.ToCharArray()).ToArray();
}
Ok, you can do it without LINQ:
public static char[][] split_string(char[] str)
{
var list = new List<char[]>();
foreach (string s in (new string(str)).Split(' '))
{
list.Add(s.ToCharArray());
}
return list.ToArray();
}
But that is all trash, this is what you should be doing:
1) Accept an string:
public static char[][] split_string(string str)
{
var list = new List<char[]>();
foreach (string s in str.Split(' '))
{
list.Add(s.ToCharArray());
}
return list.ToArray();
}
2) return using string:
public static string[] split_string(string str)
{
var list = new List<string>();
foreach (string s in str.Split(' '))
{
list.Add(s);
}
return list.ToArray();
}
3) get rid of the stuffing:
public static string[] split_string(string str)
{
return str.Split(' ');
}
4) Why did you declare a method anyway?
// ...puff...
I am new at C#, so sorry for the basic question :)
I have a text box, in this text box i write an input.
And then I want an output with only the uneven number position of the string.
So I wrote a for loop...
string strVariable = txt.Text;
for (int c = 0; c > strVariable.Length; c++)
{
string[] Array = new string[strVariable.Length];
Array [c] = strVariable.Substring(c, 1);
}
But how can I now enter all the values of the Array in one string?
So for example I have the word "Test" in the strVariable string
Then in the Array string I have "Ts"
but how can I output "Ts"
There are undoubtedly many ways to collapse an array of strings into a single string. One such way would be to use string.Concat():
var result = string.Concat(myArray);
Note that I rename your variable to myArray here. For starters, you'll want to follow language conventions with variable names which in this case specify that the first letter should be lowercase. But more importantly, you definitely don't want to name a variable with the same name as a class in a namespace that you're using. That would cause untold confusion.
I think you should use a simple for loop without using an array like in the code below :
string result;
for (int c = 0; c < txt.text.Length; c++)
{
result += txt.text.Substring(c, 1);
}