What's the difference between double quotes and single quote in C#

后端 未结 5 1117
天命终不由人
天命终不由人 2020-12-02 21:49

What\'s the difference between double quotes and single quote in C#?

I coded a program to count how many words are in a file

using System;
using Syst         


        
相关标签:
5条回答
  • 2020-12-02 22:29

    the single quote represent a single character 'A', double quote append a null terminator '\0' to the end of the string literal, " " is actually " \0" which is one byte larger than the intended size.

    0 讨论(0)
  • 2020-12-02 22:35

    Single quotes instead of double ones?

    Where? Here? if(text[i] == " ")

    text[i] gives a character/byte and this is compared to an array of (probably unicoded ??) characters/bytes. That does not work well.

    Say: compare '1' with 1
    or "1" with "one" or (2-1) with "eins" what do you think are the correct answers, or is there no meaningful answer anyway?

    Besides that: the program will not work very well with single quotes either, given the example "words.txt" =

    one word or 2 words or more words here ?

    0 讨论(0)
  • 2020-12-02 22:39

    when you say string s = "this string" then s[0] is a char at at specific index in that string (in this case s[0] == 't')

    So to answer your question, use double quotes or single quotes, you can think of the following as meaning the same thing:

    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
    }
    

    As you can see, using a single quote to determine a single char is a lot easier than trying to convert our string into a char just for testing.

    if(s[0] == " "[0]) { 
     // do something
    }
    

    is really like saying:

    string space = " ";
    if(s[0] == space[0]) {
     // do something
    }
    

    Hopefully I did not confuse you more!

    0 讨论(0)
  • 2020-12-02 22:40

    you are looking for spaces, this can be done as a space in a string or as a char. So in my opinion this would work.

    (By the way, if the file contains sentences with dots. And someone forgot to add a space after the dot, the word will not be added to the total amount of words)

    0 讨论(0)
  • 2020-12-02 22:44

    Single quotes encode a single character (data type char), while double quotes encode a string of multiple characters. The difference is similar to the difference between a single integer and an array of integers.

    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];
    
    0 讨论(0)
提交回复
热议问题