1. 我该如何将字符串变量的内容存储到文本文件中?
2. 我该如何在字符串变量中搜索特定文本,例如查找字符串中是否包含单词“book”?
要将文件保存为文本,你可以进行以下操作:
System.IO.File.WriteAllText("C:\your_path\your_file", Your_contents);
在字符串中搜索某个内容:
var position = Your_string.IndexOf("Book");
如果位置等于-1,那么你要搜索的内容就不存在。
File.WriteAllText("MyFile.txt", myString); // Write all string to file
var wordBookIndex = myString.IndexOf("book"); // If the string is found, index != -1
如果你确实不知道在哪里找到这些信息,那么很简单:
System.IO.File.WriteAllText(myPathToTheFile, myStringToWrite);
myString.Contains(someOtherString); // boolean
myString.IndexOf(someOtherString); // find the 0 based index of the target string
System.IO 命名空间提供了各种文件(和其他)IO 的方法和类,这个可能会轻松地满足您的需求:
http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx
如果要在单个字符串中进行搜索,请使用String.IndexOf:
http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx
回答第一个问题
在没有可用于将文本写入文件的类的情况下,可以利用System.IO命名空间
回答第二个问题
您可以使用正则表达式或利用IndexOf函数在字符串中搜索特定单词