C#子字符串替代-返回字符后字符串中的其余行 [英] C# Substring Alternative - Return rest of line within string after character

查看:50
本文介绍了C#子字符串替代-返回字符后字符串中的其余行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以读取文本文件并将其设置为字符串.文本文件的每一行都包含我尝试提取的单独的数据参数.这是字符串/文本文件的布局方式的一个小示例:

I have some code that reads a text file and sets it to a string. Each line of the text file contains separate data parameters that I a trying to extract. Here is an small example of how the string/text file is laid out:

...
part=XYZ
quantity=123
weight=14
length=60
...

是否有一种很好的方法可以在给定的行上返回"="之后的所有内容?

Is there a good way to return everything after "=" on a given line?

我目前可以使用子字符串来工作,但是我很好奇是否有更简洁的方法来获得相同的结果.这是我目前拥有的代码:

I currently got it to work using substring, but I'm curious if there is a more concise way to get the same result. Here is the code I currently have:

    strStart = partData.IndexOf("part=") + 5;
    strEnd = partData.IndexOf(" ", strStart);
    string partNum = partData.Substring(strStart, strEnd - strStart);

其他说明

Additional Clarification

我将从文本文件中提取多个变量.例如,鉴于上述数据,我将提取4个变量:

I will be extracting multiple variables from the text file. For example, given the data above I would extract the 4 variables:

partNum ="XYZ"

partNum = "XYZ"

qty ="123"

qty = "123"

wght ="14"

wght = "14"

len ="60"

len = "60"

推荐答案

是的,您可以更加简洁地完成它.

Yes, you can do it much more concisely.

string partNum = partData.Substring(partData.IndexOf("=") + 1);

这使用

This uses the overloaded version of String.Substring that only accepts one parameter, the starting position in the string. It continues from that point to the end of the string.

很明显,这仅在您确定 partData 中存在等号的情况下有效,而您发布的原始代码也将适用.

Clearly this only works if you're certain that there is equals sign in your partData, but so would the original code you posted.

这篇关于C#子字符串替代-返回字符后字符串中的其余行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆