I have a string containing mostly chinese characters, like so:
string sentence = "我想找到从夏洛特飞往拉斯维加斯,让站在圣路易斯";
How can I split the sentence by character? Ultimately, I want to be able to take my string, and write it to a file with each character being on its own line, like so:
我
想
找
到
从
夏
洛
特
飞
往
拉
斯
维
加
斯
,
让
站
在
圣
路
易
斯
I tried doing this:
StringBuilder s = new StringBuilder();
foreach (char character in sentence.ToCharArray())
{
s.Append(character + '\n');
}
string output = s.ToString();
StreamWriter writer = new StreamWriter("test.txt", false, Encoding.UTF8);
writer.Write(output);
writer.Close();
...but for whatever reason, instead of writing chinese characters, it writes
29252242105020184228092794129315391442445825299260413251021162260416530235763314592232222317363452614126041
...to the file instead. However, doing
StreamWriter writer = new StreamWriter("text.txt", false, Encoding.UTF8);
writer.Write(sentence);
writer.Close();
...does successfully write the Chinese sentence to the file, so I do know it shouldn't be a problem with how I'm writing to the file.
I think the problem may be that (character + '\\n'); is being interpreted as an integer. Perhaps trying adding a cast to that line or making two seperate appends like so:
s.Append(character);
s.Append('\n');
var sentence = "我想找到从夏洛特飞往拉斯维加斯,让站在圣路易斯";
var chars = sentence.ToCharArray();
using (var writer = new StreamWriter("test.txt", false, Encoding.UTF8))
{
foreach (var c in chars)
{
writer.WriteLine(c);
}
writer.Close();
}
Works fine for me
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.