Strings (Manipulation, Common Operations)
Appearance
3.5.2 Strings (Manipulation, Common Operations)
You've already learned that a String is a reference data type that holds a sequence of characters, like words or sentences. But what can you do with strings? How do you change them or get parts of them?
String Manipulation refers to all the different ways you can work with and change strings in your program. Because text is such a common type of data, programming languages provide many useful tools (often as built-in functions or methods) for handling strings.
Here are some common operations you can perform on strings:
- Concatenation (Joining Strings):
- This means putting two or more strings together to form a new, longer string.
- Often done using the
+
symbol. - Example:
"Hello" + " " + "World"
would result in"Hello World"
.
- Length (Getting the Size):
- Finding out how many characters are in a string.
- Example: The length of
"Computer"
is 8.
- Accessing Characters (Getting Parts of the String):
- Just like with arrays, you can often get a specific character from a string using its index. Remember, indexing usually starts from 0!
- Example: In
"Apple"
, the character at index 0 is'A'
, and at index 4 is'e'
.
- Substring (Getting a Piece of the String):
- Extracting a smaller piece (a "substring") from a larger string. You usually specify where the piece starts and where it ends.
- Example: Taking the substring from
"Programming"
starting at index 3 for 4 characters might give you"gram"
.
- Searching (Finding Text):
- Checking if a string contains another specific piece of text.
- Example: Is "apple" found inside "pineapple"? Yes. Is "banana" found inside "pineapple"? No.
- Replacing (Changing Text):
- Finding a specific part of a string and changing it to something else.
- Example: Replacing all "e"s with "x"s in "Hello" would result in "Hxllx".
- Changing Case (Uppercase/Lowercase):
- Converting all letters in a string to uppercase or lowercase.
- Example: Converting "Hello World" to uppercase results in "HELLO WORLD".
- Trimming (Removing Extra Spaces):
- Removing any extra spaces from the beginning or end of a string.
- Example: Trimming
" hello "
would result in"hello"
.
Strings are very flexible and powerful, and these manipulation techniques are used all the time in programming, whether you're processing user input, formatting messages, or working with text files.
Bibliography:
- W3Schools - Python String Methods: https://www.w3schools.com/python/python_strings_methods.asp
- GeeksforGeeks - String in C++: https://www.geeksforgeeks.org/cpp/strings-in-cpp/ (Discusses string operations)
- Wikipedia - String (computer science): https://en.wikipedia.org/wiki/String_(computer_science)