how to read file and pass data into array . c# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
i want to add all the numbers from notepad to the array, give me the solution .
notepad file content see photos:

If what you are trying to do is parse every number in the text file of yours to a Int32 and have a int array.
You would want to use File.ReadAllLines, to read every line from the file, string.Split each line by ';' and then parse every string number to a Int32:
string[] lines = File.ReadAllLines("numbers.txt");
List<int> numbers = new List<int>();
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (!string.IsNullOrEmpty(line))
{
string[] stringNumbers = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < stringNumbers.Length; j++)
{
if (!int.TryParse(stringNumbers[j], out int num))
{
throw new OperationCanceledException(stringNumbers[j] + " was not a number.");
}
numbers.Add(num);
}
}
}
int[] array = numbers.ToArray();
If you are looking to have a string array of the numbers then just do as the above, but without the int.TryParse and have numbers be a List<string> instead of List<int>

Related

find and extract a number from a string C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
"O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000"
extract :
1.2275000
2.3060000
3.3260000
....
It would be :
string temp = yourText;
List<int> numbers = new List<int>();
Regex re = new Regex(#"\d+");
Match m = re.Match(temp);
while (m.Success)
{
numbers.Add(Convert.ToInt32(m.Value));
temp = temp.Substring(m.Index + m.Length);
m = re.Match(temp);
}
First of all, you mentioned "from these strings", though you gave a single string. I am not clear about this part.
Secondly, what do you mean by extract? Do you want to find the position of a number in the string? If yes then you can simply use string search as following
string str = "O:2275000 BF:3060000 D:3260000";
int index = str.IndexOf("3060000");
if (index != -1)
{
Console.WriteLine(index);
}
else
{
Console.WriteLine("Not Found");
}
Or if the problem is stated like that: you were given a string and you want to extract the numbers out of it, then you can do it like so:
List<decimal> findNumbers(string str)
{
List<decimal> x = new List<decimal>();
string tokens = "";
foreach (char ch in str)
{
if (Char.IsNumber(ch))
{
tokens = tokens + ch;
}
if (!Char.IsNumber(ch) && !String.IsNullOrEmpty(tokens))
{
decimal num = Convert.ToDecimal(tokens);
x.Add(Convert.ToDecimal(num));
tokens = "";
}
}
if (String.IsNullOrEmpty(tokens))
{
x.Add(Convert.ToDecimal(tokens));
}
return x;
}
this function returns the list of numbers available in the string.
We can try using string split here:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
foreach (string n in numbers)
{
Console.WriteLine(n);
}
This prints:
2275000
3060000
3260000
You can do this in a single line with Linq.
string numbers = "O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000";
List<int> list = numbers.Split(' ').Select(x => Convert.ToInt32(string.Concat(x.Where(Char.IsDigit)))).ToList();
Tim Biegeleisen's answer is correct except it does not produce floating point output as you mentioned in your question. In his answere, just replace foreach loop with for statement, like this:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0}.{1}", i+1, numbers[i]);
}

To join comma separated in string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the below code i want the string value to be comma separated but it produces the result like testtest1test2 .But i want to display like test,test1,test2.Pls help me.
string Save=string.Empty;
for (int i = 0; i < files.Count; i++)
{
//i=0 test ,i=1 test1....
Save += nFIleUpload.OrgFileName;// display value like testtest1test2..
}
string s = string.Join(",", Save);
Change this code
string Save=string.Empty;
for (int i = 0; i < files.Count; i++)
{
Save += nFIleUpload.OrgFileName;// display value like testtest1test2..
}
string s = string.Join(",", Save);
to the following
var Save = new List<string>();
for (int i = 0; i < files.Count; i++)
{
Save.Add(nFIleUpload.OrgFileName);// display value like testtest1test2..
}
var s = string.Join(",", Save);
And to go off of MethodMan's answer, when you get tired of seeing the same value added to Save for each iteration, make sure to use that index.
var Save = new List<string>();
for (int i = 0; i < files.Count; i++)
{
Save.Add(nFIleUpload[i].OrgFileName);// display value like testtest1test2..
}
var s = string.Join(",", Save);
If nFIleUpload is actually the variable that holds the strings.. is it the files variable? Who watches the watchmen? These are the questions to ask..
Try it using an array, for sample:
string[] save = new string[files.Count];
for (var i = 0; i < files.Count; i++)
save[i] = nFIleUpload.OrgFileName;
// join all values
string s = string.Join(",", save);
Or use a stringBulder which is better to concat strings, for sample:
// define the stringBuilder
StringBuilder text = new StringBuilder();
// define the loop to concat all values separated by ',' comma
for (var i = 0; i < files.Count; i++)
text.AppendFormat("{0},", nFIleUpload.OrgFileName);
// get the output
string s = text.ToString();
// remove the last comma if necessary
if (s.EndsWith(","))
s = s.Remove(s.Length - 1);

How to convert boxed two dimensional string to 2 dimensional integer array and viceversa in c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have String which have a 2 dimensional array i need to convert these 2D string to integer array.
example:
String temp ="[[0xFF008041, 0x24008086, 0x00000000, 0x00000000,0x0008383A]]".
I need the 2D string value to 2d Integer array and viceversa
Try this
static void Main(string[] args)
{
String temp = "[[0xFF008041, 0x24008086, 0x00000000, 0x00000000,0x0008383A]]";
temp = temp.Replace("[", "");
temp = temp.Replace("]", "");
string[] tempArray = temp.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
uint[] tempIntArray = tempArray.Select(x => FromHex(x)).ToArray();
}
static uint FromHex(string value)
{
uint results;
uint.TryParse(value.Substring(2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out results);
return results;
}​
Well, since it's .Net 2.0 you can't use the benefits of more modern versions such as Linq, I would suggest using Split, for loops, Trim, and Convert:
Note #1: I'm working under the assumption that the numbers in the string will always be hex numbers.
Note #2: I'm returning a jagged array and not a multidimensional array, since you can't enforce all the inner arrays in the string to have the same number of elements.
String temp = "[[0xFF008041, 0x24008086, 0x00000000, 0x00000000,0x0008383A], [0x0008, 0x0034B]]";
int[][] ConvertStringToJaggedArray(String input)
{
String[] Separator = { "],[", "], [", "] ,[" };
String[] OuterArray = input.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
int[][] TargetArray = new int[OuterArray.Length][];
string HexString;
for (int i = 0; i < OuterArray.Length; i++)
{
String[] InnerArray = OuterArray[i].Split(',');
TargetArray[i] = new int[InnerArray.Length];
for (int j = 0; j < InnerArray.Length; j++ )
{
HexString = InnerArray[j].Trim(" []".ToCharArray());
TargetArray[i][j] = Convert.ToInt32(HexString, 16);
}
}
return TargetArray;
}

Why parsing string of path name is not working? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this code:
List<string> dirParts = new List<string>();
int index = 0;
for (int i = 0; i < dirName.Length; i++)
{
index = dirName.IndexOf("/");
string dironly = dirName.Substring(index, dirName.Length - index);
dirParts.Add(dironly);
}
dirName for example contains d/1/2/3/4/5
So I need that in the List dirParts in the end I will have in index 0 d, in index 1 d/1, in index 2 d/1/2, in index 3 d/1/2/3, in index 4 d/1/2/3/4, in index 5 d/1/2/3/4/5
So when I look on the List it should look like this:
d
d/1
d/1/2
d/1/2/3
d/1/2/3/4
d/1/2/3/4/5
Possible implementation:
List<string> dirParts = new List<string>();
int index = -1;
while (true) {
index = dirName.IndexOf("/", index + 1);
if (index < 0) {
dirParts.Add(dirName);
break;
}
else
dirParts.Add(dirName.Substring(0, index));
}
Apart from the fact that this kind of path manipulation is best left to the library, lest your code breaks on strange exceptional directory names, your code works as it does because you look everytime for the same "/".
You should search after the last one:
index = dirName.IndexOf("/", index+1);
If you really want to do it that way:
for (int i = 0; i < dirName.Length; i++) {
index = dirName.IndexOf("/", index);
if (index == -1)
i = index = dirName.Length; //last one
dirParts.Add(dirName.Substring(0, index++));
}
If it's a directory, I like to use Path library personally. The only issue would be the use of / over \ in directory name, so you'd have to call .Replace before inserting:
var orig = "d/1/2/3/4/5"; // Original string
List<String> dirParts = new List<String>(new[]{ orig }); // start out with list of original
// Get the directory below this one. (drop off last folder)
String part = Path.GetDirectoryName(orig);
while (!String.IsNullOrEmpty(part))
{
// add it to the first entry in the list
dirParts.Insert(0, part.Replace('\\','/'));
// get the next parent folder.
part = Path.GetDirectoryName(part);
}
/* dirParts = [ "d", "d/1", "d/1/2", ... ] */
However, if you're just looking for the down and dirty LINQ approach:
var orig = "d/1/2/3/4/5";
String[] parts = orig.Split('/');
var dirParts = Enumerable.Range(1, parts.Length)
.Select (e => String.Join("/", parts.Take(e)));

replace string by index of this string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hello so i have a text file that looks like
45353
b
4353
b
54
54
b
5345
53453
and array list that looks like
A
B
A
how can i replace string b->A b - > b - > A ?
OUTPUT SHOUDL LOOK like
45353
A
4353
B
54
54
A
5345
53453
string content = File.ReadAllText("data.txt");
var replacements = new[] { "A", "B", "A" };
int index = 0;
string result = Regex.Replace(content, #"[a-zA-Z]+",
m => replacements.Length > index ?
replacements[index++] : m.Value);
This will execute MatchEvaluator for each found word, and replace it with value from appropriate position in replacements array.
You could use Regex.Replace(String, String, Int32) for this, execute until all of the intended replacements from arr are replaced.
var text = File.ReadAllText("file.txt");
var arr = new[] { "A", "B", "A" };
var regex = new Regex("b");
for(int i = 0; i < arr.Count; i++)
text = regex.Replace(text, arr[i].ToString(), 1);
Tip: Never answer when tired...
Read the 2nd file into an array of strings
Keep a counter initialized to 0
Read from the 1st file, every-time your data matches the replacement condition, replace it with the value at the counter and increment the counter
StreamReader sr = new StreamReader("file.txt");
int counter = 0;
List<string> arrayFromFile = new List<string>();
while(string line = sr.ReadLine())
{
if(line=='b')
{
line = abaArray[counter];
counter++;
if(counter>=abaArray.Length)
{
counter=0;
}
}
arrayFromFile.Add(line)
}
//Write back to the file

Categories

Resources