开发者

Foreach wont split a string

开发者 https://www.devze.com 2022-12-27 04:00 出处:网络
//assign variables string measurementIn; //read in file in array string[] lines = File.ReadAllLines(\"../../convert.txt\");
//assign variables
        string measurementIn;


        //read in file in array
        string[] lines = File.ReadAllLines("../../convert.txt");

        //ask user for date
        Console.WriteLine开发者_JAVA百科("Enter the conversion in the form (amount,from,to)");
        measurementIn = Console.ReadLine();

        //array for splitting input
        string[] conversionArray = measurementIn.Split(',');

        Console.WriteLine("{0} , {1} , {2}", conversionArray[0], conversionArray[1], conversionArray[2]);
        Console.ReadLine();

        //check lines for conversion
        foreach (string line in lines)
        {
            //array for the measurement
            string[] measurementArray = line.Split(',');

            Console.WriteLine("{0}", measurementArray[0]);

The problem lies at the end, the stuff inside foreach


maybe u search somthing like this?

in Txt:

Dog,Cat,Mouse,Fish,Cow,Horse,Hyena
Programmer,Wizard,CEO,Rancher,Clerk,Farmer

code:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        int i = 0;
        foreach (string line in File.ReadAllLines("TextFile1.txt"))
        {
            string[] parts = line.Split(',');
            foreach (string part in parts)
            {
                Console.WriteLine("{0}:{1}",
                    i,
                    part);
            }
            i++;
        }
    }
}

output:

0:Dog
0:Cat
0:...
1:Programmer
1:...

Where i got it: http://dotnetperls.com/string-split

just tried something:

StreamReader convert = new StreamReader("../file.txt");

string line = convert.ReadLine();
String inputMeasurement = Console.ReadLine();
string[] inputMeasurementArray = inputMeasurement.Split(',');
while (line != null)
{
    string[] fileMeasurementArray = line.Split(',');
    if (fileMeasurementArray[0] == inputMeasurementArray[1])
    {
        if (fileMeasurementArray[1] == inputMeasurementArray[2])
        {
            Console.WriteLine("{0}", fileMeasurementArray[2]);
        }
        else
        {
            Console.WriteLine("False");
        }

    }
    else
    {
        Console.WriteLine("False");
    }
    line = convert.ReadLine();
}
Console.ReadKey();


Try using a StreamReader to read in lines from the file instead using File.ReadAllLine() and then looping over each line. Like this:

StreamReader convert = new StreamReader("filename.txt");

string line = convert.ReadLine();

while (line != null)
{
    string[] measurementArray = line.Split(',');
    Console.WriteLine("{0}", measurementArray[0]);
    Console.WriteLine("{0}", measurementArray[1]);
    line = convert.ReadLine();
}

You'll need add "using System.IO;".

0

精彩评论

暂无评论...
验证码 换一张
取 消