在C#中双引号和单引号有什么区别?
我编写了一个程序来计算一个文件中有多少个单词
using System;
using System.IO;
namespace Consoleapp05
{
class Program
{
public static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"C:\words.txt");
string text = sr.ReadToEnd();
int howmany = 0;
int howmany2 = 0;
for(int i = 0; i < text.Length; i++)
{
if(text[i] == " ")
{
howmany++;
}
}
howmany2 = howmany + 1;
Console.WriteLine("It is {0} words in the file", howmany2);
Console.ReadKey(true);
}
}
}
这给了我一个错误,因为双引号。我的老师告诉我用单引号代替,但他没有告诉我为什么。那么在C#中双引号和单引号有什么区别呢?
发布于 2009-03-02 11:48:51
单引号编码单个字符(数据类型char
),而双引号编码多个字符的字符串。这种差异类似于单个整数和整数数组之间的差异。
char c = 'c';
string s = "s"; // String containing a single character.
System.Diagnostics.Debug.Assert(s.Length == 1);
char d = s[0];
int i = 42;
int[] a = new int[] { 42 }; // Array containing a single int.
System.Diagnostics.Debug.Assert(a.Length == 1);
int j = a[0];
发布于 2009-03-02 21:28:21
当您说string s= "this string“时,s是字符串中特定索引处的字符(在本例中为s == 't')
所以,为了回答你的问题,使用双引号或单引号,你可以认为下面的意思是相同的:
string s = " word word";
// check for space as first character using single quotes
if(s[0] == ' ') {
// do something
}
// check for space using string notation
if(s[0] == " "[0]) {
// do something
}
正如您所看到的,使用单引号来确定单个字符比仅为了测试而尝试将字符串转换为字符要容易得多。
if(s[0] == " "[0]) {
// do something
}
实际上就像是在说:
string space = " ";
if(s[0] == space[0]) {
// do something
}
希望我没有让你更困惑!
发布于 2015-12-16 07:08:39
单引号表示单字符'A'
,双引号将空终止符'\0'
附加到字符串文字的末尾," "
实际上是" \0"
,它比预期大小大一个字节。
https://stackoverflow.com/questions/602033
复制相似问题