更新时间:2023-11-07 17:06:40
以下应能起作用:
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.