将LastIndexOf和Substring与数组一起使用

本文关键字:一起 数组 LastIndexOf Substring | 更新日期: 2023-09-27 18:27:15

基本上,我从一个文本文件中读取50行,每行的格式都有点像这样:

David Chalmers 34

我已经使用ReadAllLines读取了文本文件,因此数组中的每一行都应该是不同的条目。

我试图从每一行中提取数字,并将它们存储到自己的数组中。现在我得到错误:

索引和长度必须引用字符串中的某个位置。

static void getResults(string[] Text)
{
    // X = lastIndexOf for ' ' (space)
    // x will take position of the last space
    // Results = substring
    // z will be the length of the string
    // z = text.Length
    //  Substring (x+1,z-x+1)
    int lines = 50;
    string[] Results = new string[lines];
    for (int i = 0; i < Text.Length; i++)
    {
        int x = Text[i].LastIndexOf(' ');
        int z = Text[i].Length;
        Results[lines] = Text[i].Substring(x + 1, z - x + 1);
    }
}

任何帮助都将不胜感激!

将LastIndexOf和Substring与数组一起使用

使用拆分,它更容易:

String Test = "David Chalmers 34";
String[] Segments = Test.Split(' ');
Console.WriteLine(Segments[2]);
Console.ReadKey();

当然,您会希望为错误输入添加错误处理。

必须从子字符串长度中减去1,而不是相加:

var line = "David Chalmers 34";
var lineLength = line.Length; // == 17
var lastSpacePosition = line.LastIndexOf(' '); // == 14
var age = line.Substring(lastSpacePosition + 1, lineLength - lastSpacePosition - 1); // == 34

您的表达式应该是:

Results[lines] = Text[i].Substring(x + 1, z - x - 1);

您需要减去1而不是添加。

您也可以在Linq:的一行中完成所有这些

var Results = Text.Take(50)
    .Select(line => line.Split(' '))
    .Select(sa => sa.Last())
    .ToArray();

下面是我要做的,使用Person类。考虑到你的项目范围,现在可能没有必要这样做,但如果范围不断扩大,使用类和实例会有回报。此外,这样,你就有了与你所寻求的年龄相匹配的名称,这在某个时候可能是必要的。

public static List<Person> GetResults(string[] text)
{
    var results = new List<Person>();
    foreach(var line in text)
    {
        results.Add(Person.Parse(line));
    }
    return results;
}
public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    public static Person Parse(string fromInputLine)
    {
        ValidateInput(fromInputLine);
        var delimPosition = fromInputLine.LastIndexOf(' ');
        var name = fromInputLine.Substring(0, delimPosition);
        var age = Convert.ToInt32(fromInputLine.Substring(delimPosition + 1));
        return new Person(name, age);
    }
    private static void ValidateInput(string toValidate)
    {
        if (!System.Text.RegularExpressions.Regex.IsMatch(toValidate, @"^.+'s+'d+$")) 
            throw new ArgumentException(string.Format(@"The provided input ""{0}"" is not valid.", toValidate));
    }
}

你可以使用这个方法。从字符串类中分离,他所做的是用空格分隔字符串,然后你得到一个字符串数组。。。

var entry = "David Chambers 34";
string[] result = entry.Split(" ")

然后你可以转换成整数

var age = Convert.ToInt32(result[2]);

var age = Int32.TryParse(result[2]);

要将数字存储在自己的数组中,可以尝试:

string[] numbers = text.Select(x => x.Substring(x.LastIndexOf(' '))).ToArray();

使用StringReader

        static void getResults(string Text)
        {
            // X = lastIndexOf for ' ' (space)
            // x will take position of the last space
            // Results = substring
            // z will be the length of the string
            // z = text.Length
            //  Substring (x+1,z-x+1)
            StringReader reader = new StringReader(Text);
            List<string> Results = new List<string>();
            string inputLine = "";
            while ((inputLine = reader.ReadLine()) != null)
            {
                Results.Add(inputLine.Trim());
            }
        }
​