dance dance
dance dance

Reputation: 93

character "^$" in string

it may be a naive question, but i don't know what these codes do

"^$","^","$"

in function

 string preProcess(string s) 
  {
    int n = s.length();
    if (n == 0) return "^$";
    string ret = "^";

   for (int i = 0; i < n; i++)
    ret += "#" + s.substr(i, 1); 

    ret += "#$";
    return ret;
}

The purpose of the function is to insert "#" between every character in string s. For example, change string "aba" to "#a#b#a#". I couldn't figure out what "^$" does here. And if I change them, it causes run time error.

Thanks !

Upvotes: 0

Views: 66

Answers (1)

Carl Norum
Carl Norum

Reputation: 225052

^ is a start of line marker. $ is an end of line marker. If the input is empty, this function just returns ^$, an empty line. Otherwise it returns "^...$" where the ... is interleaved with # as you describe.

The ^ and $ were likely chosen because of their use as start- and end-of-line markers in most varieties of regular expressions.

Upvotes: 3

Related Questions