将C#中的字符串变量存储到文本文件.txt中。

10
1. 我该如何将字符串变量的内容存储到文本文件中? 2. 我该如何在字符串变量中搜索特定文本,例如查找字符串中是否包含单词“book”?
5个回答

23

要将文件保存为文本,你可以进行以下操作:

System.IO.File.WriteAllText("C:\your_path\your_file", Your_contents);

在字符串中搜索某个内容:

var position = Your_string.IndexOf("Book");

如果位置等于-1,那么你要搜索的内容就不存在。


6
File.WriteAllText("MyFile.txt", myString); // Write all string to file
var wordBookIndex = myString.IndexOf("book"); // If the string is found, index != -1

6

如果你确实不知道在哪里找到这些信息,那么很简单:

System.IO.File.WriteAllText(myPathToTheFile, myStringToWrite);

要在一个字符串中查找另一个字符串,您只需要这样做:
myString.Contains(someOtherString); // boolean
myString.IndexOf(someOtherString); // find the 0 based index of the target string

1

0

回答第一个问题

在没有可用于将文本写入文件的类的情况下,可以利用System.IO命名空间

回答第二个问题

您可以使用正则表达式或利用IndexOf函数在字符串中搜索特定单词


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接