61 c#
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于双引号,这给了我一个错误.我的老师告诉我改为使用单引号,但他并没有告诉我原因.那么C#中双引号和单引号之间的区别是什么?
Kon*_*lph 135
单引号编码单个字符(数据类型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];
Run Code Online (Sandbox Code Playgroud)
当你说string s ="this string"时,s [0]是该字符串中特定索引处的char(在这种情况下为s [0] =='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
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,使用单引号来确定单个char比尝试将字符串转换为char以进行测试要容易得多.
if(s[0] == " "[0]) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
真的很喜欢说:
string space = " ";
if(s[0] == space[0]) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
希望我没有更多的混淆你!