Function: substring

substring is a function defined in fns.c.

Signature

(substring STRING &optional FROM TO)

Documentation

Return a new string whose contents are a substring of STRING.

The returned string consists of the characters between index FROM
(inclusive) and index TO (exclusive) of STRING. FROM and TO are
zero-indexed: 0 means the first character of STRING. Negative values are counted from the end of STRING. If TO is nil, the substring runs to the end of STRING.

The STRING argument may also be a vector. In that case, the return value is a new vector that contains the elements between index FROM
(inclusive) and index TO (exclusive) of that vector argument.

With one argument, just copy STRING (with properties, if any).

Other relevant functions are documented in the string group.

Probably introduced at or before Emacs version 15.

Shortdoc

;; string
(substring "foobar" 0 3)
    => "foo"
  (substring "foobar" 3)
    => "bar"

Source Code

// Defined in /usr/src/emacs/src/fns.c
{
  Lisp_Object res;
  ptrdiff_t size, ifrom, ito;

  size = CHECK_VECTOR_OR_STRING (string);
  validate_subarray (string, from, to, size, &ifrom, &ito);

  if (STRINGP (string))
    {
      ptrdiff_t from_byte
	= !ifrom ? 0 : string_char_to_byte (string, ifrom);
      ptrdiff_t to_byte
	= ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
      res = make_specified_string (SSDATA (string) + from_byte,
				   ito - ifrom, to_byte - from_byte,
				   STRING_MULTIBYTE (string));
      copy_text_properties (make_fixnum (ifrom), make_fixnum (ito),
			    string, make_fixnum (0), res, Qnil);
    }
  else
    res = Fvector (ito - ifrom, aref_addr (string, ifrom));

  return res;
}