Programs of String Operations

Implement string and set operations on the arrays.

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:

Press + to interact
Press + to interact
src = 'Just a string' # The string to be copied
lsrc = src.length # Calculating the length of src
dst = '' # Creating an empty string
for index in 0...lsrc
dst += src[index] # Copying data from src to dst character by character
end
print(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:

Press + to interact
str1 = 'Just a' # The string 1
str2 = ' string' # The string 2
str3 = '' # Creating empty string to store the concatenation result
for ind in 0...str1.length
str3 += str1[ind] # Appending the values of str1 to str3
end
for ind2 in 0...str2.length
str3 += str2[ind2]# Appending the values of str3 to str2
end
print(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
Press + to interact
p = ['25','55','888','9','30','45'] # The 1st array which we want to search
lp = p.length # Calculate the length of array p
r = '50' # The string to be searched
i = 0
found = 0
while i<lp # This loop will terminate when i is not less than lp
if (r == p[i]) # If the element of p contains r
print(r," is found at index ",i,"\n")
found = 1 # Update the variable found with 1
end
i += 1
end
if found == 0
print(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'
Press + to interact
p = 'was it a car or a cat i saw' # The string to be reversed
print("\nORIGINAL string is: ",p)
lp = p.length # Calculating length of string p
q = '' # empty string to store the reverse
i = 1
found = 0
while i<=lp # This loop will terminate when i is greater than lp
q += p[-i] # Appending the characters of p to q in a backward fashion
i += 1
end
print("\nREVERSED string is: ",q)