Programs of String Operations
Implement string and set operations on the arrays.
We'll cover the following
Copy a string
In Ruby, the individual characters in a string can be accessed but not assigned or modified.
The following program copies a string to another string:
src = 'Just a string' # The string to be copiedlsrc = src.length # Calculating the length of srcdst = '' # Creating an empty stringfor index in 0...lsrcdst += src[index] # Copying data from src to dst character by characterendprint(src,"\n")print(dst,"\n")
String concatenation
Concatenation means appending a string to another string. The following program concatenates two strings and stores them to another string:
str1 = 'Just a' # The string 1str2 = ' string' # The string 2str3 = '' # Creating empty string to store the concatenation resultfor ind in 0...str1.lengthstr3 += str1[ind] # Appending the values of str1 to str3endfor ind2 in 0...str2.lengthstr3 += str2[ind2]# Appending the values of str3 to str2endprint(str1,"\n")print(str2,"\n")print(str3,"\n")
Search a string in an array of strings
The following program checks whether a string or character is present in a string element.
Sample array
p = ['25','55','888','9','30','45']
Sample value 1 of to be searched
5
Sample output 1
5 is found at index 0
5 is found at index 1
5 is found at index 5
Sample value 2 of to be searched
50
Sample output 2
50 is NOT FOUND in the array
p = ['25','55','888','9','30','45'] # The 1st array which we want to searchlp = p.length # Calculate the length of array pr = '50' # The string to be searchedi = 0found = 0while i<lp # This loop will terminate when i is not less than lpif (r == p[i]) # If the element of p contains rprint(r," is found at index ",i,"\n")found = 1 # Update the variable found with 1endi += 1endif found == 0print(r," is NOT FOUND in the array\n")end
Reverse a string
The following program stores the reverse of a string to another string:
Sample string
'was it a car or a cat I saw'
Sample output
ORIGINAL string is: 'was it a car or a cat i saw'
REVERSED string is: 'was i tac a ro rac a ti saw'
p = 'was it a car or a cat i saw' # The string to be reversedprint("\nORIGINAL string is: ",p)lp = p.length # Calculating length of string pq = '' # empty string to store the reversei = 1found = 0while i<=lp # This loop will terminate when i is greater than lpq += p[-i] # Appending the characters of p to q in a backward fashioni += 1endprint("\nREVERSED string is: ",q)