Find the indices of
the first and last space in a given string. Character indexing starts at 0.
Input. One string
containing only Latin letters, punctuation marks, and spaces.
Output. Print two numbers:
the index of the first space and the index of the last space in the string. If
there are no spaces in the string, print -1.
Sample input 1 |
Sample output 1 |
I am programming on
Python. |
1 19 |
|
|
Sample input 2 |
Sample output 2 |
abrakadabra |
-1 |
strings
Declare two variables:
· a is the index of the first space;
· b is the index of the last space;
Initialize
them as a = b = -1. Next, iterate over the characters
of the string s. If the current character is a space (si = ‘ ‘):
·
If no spaces have been encountered before (a = -1), set a = i;
·
In any case, update b = i;
After completing the iteration:
·
If there are no spaces in the string (a = -1), print
-1.
·
Otherwise, print the indices of the first and last
spaces (a and b).
Algorithm implementation
Read the input string.
getline(cin, s);
Initialize
the variables a and b as the indices of the first and last
spaces.
a = b = -1;
for (i = 0; i < s.size(); i++)
If the current character si is a space:
·
If no spaces have been encountered before (a = -1), set a = i;
·
Update b = i;
if (s[i] == ' ')
{
if (a == -1) a =
i;
b = i;
}
If there are no spaces in the string (a = -1), print -1. Otherwise, print the
indices of the first and last spaces.
if (a == -1) printf("-1\n");
else printf("%d %d\n", a, b);
Python implementation
Read the input string.
s = input()
Initialize
the variables a and b as the indices of the first and last
spaces.
a = b = -1
for i in range(len(s)):
If the current character si is a space:
·
If no spaces have been encountered before (a = -1), set a = i;
·
Update b = i;
if s[i] == ' ':
if a == -1: a = i
b = i
If there are no spaces in the string (a = -1), print -1. Otherwise, print the
indices of the first and last spaces.
if a == -1:
print("-1")
else:
print(a, b)
Python implementation – find, rfind
Read the input string.
s = input()
Find the indices of the first and last space.
·
The find function returns the index of the first occurrence of a substring in a string.
·
The rfind function returns the index of the last occurrence of a
substring in a string.
Both functions return -1 if the substring is not found.
a = s.find(' ')
b = s.rfind(' ')
If there are no spaces in the string (a = -1), print -1. Otherwise, print the
indices of the first and last spaces.
if a == -1:
print("-1")
else:
print(a, b)