Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Strings Notes

Introduction to strings

 

A string is a data type in programming that is defined as a sequence of characters, it is implemented as an array of bytes (or words) that stores a sequence of elements, typically characters using some character encoding.

Depending on the programming language, strings can be of two types:

  • Mutable strings: Mutable strings are strings that can be modified. However, it depends on the declaration and the programming language.
  • Immutable strings: Immutable strings are strings that cannot be modified, the string is unique. Making any changes to the string involves creating a copy of the original string and deallocating it.

Operations on strings

 

Common string operations include finding the length, copying, concatenating, replacing, counting the occurrences of characters in a string. Such operations on strings can be performed easily with built-in functions provided by any programming language.

 

Some of the standard operations involving strings: 

  • Access characters: Retrieving characters of the string. Similar to arrays, strings follow 0-based indexing. For example, S = “apple”, ‘a’ is the character at 0th index ( S[0] ), ‘e’ is the character at 4th index of the string S ( S[4] ).
  • Concatenation: Joining characters end to end, combining strings.For example:  S1 = “Hello ”, S2 = “World.”, the concatenation of strings S1 and S2 represented by S3 is S3 = S1+S2 => “Hello World.” , while S3 = S2+S1 => “World.Hello ”.
  • Substring: A contiguous sequence of characters in a string. For example, Substrings of the string “boy” are: “”, ”b”, ”o”, ”y”, ”bo”, ”oy”, ”boy” ( an empty string is also a substring ).
    • Prefix: A prefix is any leading contiguous part of the string. For example, S = “garden” - “”, “g”, ”ga”, ”gar”, ”gard”, ”garde”,  “garden” are all prefixes of the string S.
    • Suffix: A suffix is any trailing contiguous part of the string. For example, S = “garden” - “”, ”n”, ”en”, ”den”, ”rden”, ”arden”, ”garden” are all suffixes of the string S.

NOTE: A string of length ‘N’ has (N * (N + 1)) / 2 substrings.

 

Applications of strings

  • String matching algorithms, which involve searching for a pattern in a given text have various applications in the real-world.
  • String matching algorithms contribute to efficiently implementing Spell checkers, Spam filters, Intrusion detection systems, plagiarism detection, bioinformatics, digital forensics, etc.