如何将.txt文件中文本的特定部分存储在字符串中? [英] how to store specific part of text from a .txt file in a string ?
问题描述
如何将文本文件中的文本存储在字符串中.我只想在两个自我指定的符号之间存储文本.例如
如果txt文件包含:
jhon upload_file#C:\ Myfolder#
我只想在两个#符号之间存储文本,即字符串仅存储
c:\ Myfolder
感谢
How can i store text from a text file in a string. i only want to store text between two self specified symbols..e.g
if txt file contains :
jhon upload_file # C:\Myfolder #
i only want to store text between the two # symbols i.e the string only stores
c:\Myfolder
thanks
推荐答案
以下应能起作用:
the following should work:
string strng = "dsksf#dfkfdsafl#dsfksa";
var s = strng.Substring(strng.IndexOf("#") + 1, strng.LastIndexOf("#") - strng.IndexOf("#") - 1);
var sw = new StreamWriter(@"C:\Users\clifford\Documents\text.txt");
sw.Write(s);
sw.Close();
在这里,我假设您要存储字符串,而不是保存字符串,如果要打开文本文件来获取字符串,可以使用以下命令:
Here I am assuming you want to store the string, not save the string, if you want to open a text file to get the string you can use the following:
var sr = new StreamReader(@"C:\Users\clifford\Documents\text.txt");
var x = sr.ReadToEnd();
sr.Close();
小心点,将其存储在磁盘上.
Be careful with your words, store would be to disk.
使用String.IndexOf
函数获取#字符的位置.
使用String.LastIndexOf
函数获取最后#个字符的位置.
然后,只需使用String.SubString
方法 [
Use theString.IndexOf
function to get location of the # character.
Use theString.LastIndexOf
function to get location of the last # character.
Then, just useString.SubString
method[^] to get the characters in the middle set.
Clifford的字符串切片答案还有另一种解决方案.您可以使用Regex来执行此操作.
正则表达式非常强大,非常适合字符串操作.
在您的情况下,您可以这样操作:
Hi,
There''s an alternative solution to Clifford''s string slicing answer. You could use Regex to do this.
Regex is very powerful and is a very well suited at string manipulation.
In your case you could do it like this:
string strng = "dsksf#dfkfdsafl#dsfksa";
Match match = Regex.Match(strng, "#.*#");
string result = match.Value.Substring(1, match.Value.Length - 2);
正则表达式上有很多可用资源:
http://msdn.microsoft.com/en-us/library/c75he57e.aspx [ ^ ]
http://www.regular-expressions.info/ [ http://www.pagecolumn.com/tool/regtest.htm [
There are plenty on resources on Regex available:
http://msdn.microsoft.com/en-us/library/c75he57e.aspx[^]
http://www.regular-expressions.info/[^]
There are also a few online regex testers:
http://www.pagecolumn.com/tool/regtest.htm[^]
Valery.
这篇关于如何将.txt文件中文本的特定部分存储在字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!