How to use the strip method of string in Julia
Overview
In Julia, the strip method removes the specified characters from the trailing (right side) and the leading end (left side) of the given string.
Syntax
strip(sourcestr::AbstractString, charsToBeRemoved)
Parameters
This method takes two arguments:
sourcestr: The string in which we remove the trailing and leading characters.chars: The characters which we remove.
Return value
This method returns a new string by removing the specified trailing and leading characters from the given string.
Example
# Removing the character 'r' and 'n', at the start & endprintln(strip("winner", ['r', 'w']))# Removing the character 'r', 'n', 'e', at the start & endprintln(strip("winner", ['w', 'n', 'e']))# Removing the character 'g' at the start & endprintln(strip("winner", ['g']))
Explanation
- Line 2: We use the
stripmethod with the string,winner, as the source string, and with['r', 'w'], to specify the characters to be removed from the start and end of the string.
The strip method performs two operations:
-
Loop the source string from the start and remove the character that matches ‘w’ and ‘r’. The loop will stop when a character of the source string is not present in the removable characters. In
winner, looping from the start, the first characterwis removed. The second characteriis not present in the removable characters. Therefore, the stripping process at the start of the string stops. -
Loop the source string from the start and remove the character that matches ‘w’ and ‘r’. In
winner, the last characterris removed. The second charactereis not present in the removable characters. Therefore, the stripping process at the end of the string stops.
After the above two operations, it returns the remaining part of the string as a new string. In our case, the return value is inne.
Line 5: We use the strip method with the string, winner, as the source string and with ['w', 'n', 'e'] as the characters to be removed.
The strip method returns inner as result.
Line 8: We use the strip method with the string, winner, as the source string and with ['g'] as the character to be removed.
The strip method will return winner as the output. The character g is not present in the source string. Therefore, it returns the string winner.