Skip to main content
Chapter 8 of 11
NCERT Solutions

Strings

Bihar Board · Class 11 · Computer Science

NCERT Solutions for Strings — Bihar Board Class 11 Computer Science.

45 questions25 flashcards5 concepts

Interactive on Super Tutor

Studying Strings? Get the full interactive chapter.

Quizzes, flashcards, AI doubt-solver and a step-by-step study plan — built for ncert solutions and more.

1,000+ Class 11 students started this chapter today

7 Questions Solved · 2 Sections

EXERCISE

1Consider the following string mySubject:
mySubject = "Computer Science"
What will be the output of the following string operations:
i. print(mySubject[0:len(mySubject)])
ii. print(mySubject[-7:-1])
iii. print(mySubject[::2])
iv. print(mySubject[len(mySubject)-1])
v. print(2*mySubject)
vi. print(mySubject[::-2])
vii. print(mySubject[:3] + mySubject[3:])
viii. print(mySubject.swapcase())
ix. print(mySubject.startswith('Comp'))
x. print(mySubject.isalpha())
Show solution
Given: `mySubject = "Computer Science"`

The string has 16 characters (indices 0 to 15).

C o m p u t e r S c i e n c e\text{C o m p u t e r S c i e n c e}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\text{0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}

i. `print(mySubject[0:len(mySubject)])`

`len(mySubject)` = 16, so `mySubject[0:16]` returns the entire string.

Output:
```
Computer Science
```

ii. `print(mySubject[-7:-1])`

Negative index 7-7 corresponds to index 167=916 - 7 = 9 (character `S`) and 1-1 corresponds to index 1515 (exclusive), so characters at indices 9 to 14 are returned: `S`, `c`, `i`, `e`, `n`, `c`.

Output:
```
Scienc
```

iii. `print(mySubject[::2])`

Slice with step 2 picks every alternate character starting from index 0:
- Indices: 0(`C`), 2(`m`), 4(`u`), 6(`e`), 8(` `), 10(`c`), 12(`e`), 14(`c`)

Output:
```
Cmue ce
```

iv. `print(mySubject[len(mySubject)-1])`

`len(mySubject) - 1 = 15`, so `mySubject[15]` = `'e'` (last character).

Output:
```
e
```

**v. `print(2*mySubject)`**

The `*` operator repeats the string 2 times.

Output:
```
Computer ScienceComputer Science
```

vi. `print(mySubject[::-2])`

Slice with step 2-2 starts from the last character (index 15) and moves backwards picking every alternate character:
- Indices: 15(`e`), 13(`n`), 11(`i`), 9(`S`), 7(`r`), 5(`t`), 3(`p`), 1(`o`)

Output:
```
eniSrtpo
```

vii. `print(mySubject[:3] + mySubject[3:])`

`mySubject[:3]` = `"Com"` and `mySubject[3:]` = `"puter Science"`. Concatenating them gives back the full string.

Output:
```
Computer Science
```

viii. `print(mySubject.swapcase())`

`swapcase()` converts uppercase letters to lowercase and vice versa.
- `C` → `c`, `o` → `O`, `m` → `M`, `p` → `P`, `u` → `U`, `t` → `T`, `e` → `E`, `r` → `R`, space stays, `S` → `s`, `c` → `C`, `i` → `I`, `e` → `E`, `n` → `N`, `c` → `C`, `e` → `E`

Output:
```
cOMPUTER sCIENCE
```

ix. `print(mySubject.startswith('Comp'))`

`startswith()` returns `True` if the string starts with the given prefix. `"Computer Science"` does start with `"Comp"`.

*(Note: The question has a typo `startsworth`; the correct method is `startswith`.)*

Output:
```
True
```

x. `print(mySubject.isalpha())`

`isalpha()` returns `True` only if all characters are alphabetic. `"Computer Science"` contains a space, so it returns `False`.

Output:
```
False
```
2Consider the following string myAddress:
myAddress = "WZ-1, New Ganga Nagar, New Delhi"
What will be the output of following string operations:
i. print(myAddress.lower())
ii. print(myAddress.upper())
iii. print(myAddress.count('New'))
iv. print(myAddress.find('New'))
v. print(myAddress.rfind('New'))
vi. print(myAddress.split(','))
vii. print(myAddress.split(' '))
viii. print(myAddress.replace('New', 'Old'))
ix. print(myAddress.partition(','))
x. print(myAddress.index('Agra'))
Show solution
Given: `myAddress = "WZ-1, New Ganga Nagar, New Delhi"`

i. `print(myAddress.lower())`

`lower()` converts all characters to lowercase.

Output:
```
wz-1, new ganga nagar, new delhi
```

ii. `print(myAddress.upper())`

`upper()` converts all characters to uppercase.

Output:
```
WZ-1, NEW GANGA NAGAR, NEW DELHI
```

iii. `print(myAddress.count('New'))`

`count()` returns the number of non-overlapping occurrences of the substring `'New'` in the string. `'New'` appears at positions corresponding to `"New Ganga"` and `"New Delhi"` — twice.

Output:
```
2
```

iv. `print(myAddress.find('New'))`

`find()` returns the index of the first occurrence of the substring.

Counting characters in `"WZ-1, New Ganga Nagar, New Delhi"`:
- `W`=0, `Z`=1, `-`=2, `1`=3, `,`=4, ` `=5, `N`=6

First `'New'` starts at index 6.

Output:
```
6
```

v. `print(myAddress.rfind('New'))`

`rfind()` returns the index of the last occurrence of the substring.

Counting: `"WZ-1, New Ganga Nagar, "` has 23 characters (indices 0–22), so the second `'New'` starts at index 23.

Output:
```
23
```

vi. `print(myAddress.split(','))`

`split(',')` splits the string at every comma and returns a list.

Output:
```
['WZ-1', ' New Ganga Nagar', ' New Delhi']
```

vii. `print(myAddress.split(' '))`

`split(' ')` splits the string at every single space and returns a list.

Output:
```
['WZ-1,', 'New', 'Ganga', 'Nagar,', 'New', 'Delhi']
```

viii. `print(myAddress.replace('New', 'Old'))`

`replace('New', 'Old')` replaces all occurrences of `'New'` with `'Old'`.

Output:
```
WZ-1, Old Ganga Nagar, Old Delhi
```

ix. `print(myAddress.partition(','))`

`partition(',')` splits the string at the first occurrence of `','` and returns a tuple of three parts: (before separator, separator, after separator).

Output:
```
('WZ-1', ',', ' New Ganga Nagar, New Delhi')
```

x. `print(myAddress.index('Agra'))`

`index()` raises a `ValueError` if the substring is not found. `'Agra'` does not exist in `myAddress`.

Output:
```
ValueError: substring not found
```

PROGRAMMING PROBLEMS

1Write a program to input line(s) of text from the user until enter is pressed. Count the total number of characters in the text (including white spaces), total number of alphabets, total number of digits, total number of special symbols and total number of words in the given text. (Assume that each word is separated by one space).Show solution
Concept Used:
- `input()` to read lines until an empty line (Enter) is pressed.
- String methods `isalpha()`, `isdigit()` to classify characters.
- A character that is neither alphabetic nor a digit nor a space is a special symbol.
- Words are counted by splitting on spaces.

Program:

```python
total_chars = 0
total_alpha = 0
total_digits = 0
total_special = 0
total_words = 0

print("Enter lines of text (press Enter on empty line to stop):")

while True:
line = input()
if line == "": # Stop when user presses Enter on empty line
break
total_chars += len(line)
for ch in line:
if ch.isalpha():
total_alpha += 1
elif ch.isdigit():
total_digits += 1
elif ch == ' ':
pass # spaces counted in total_chars but not special
else:
total_special += 1
# Count words (each word separated by one space)
words = line.split(' ')
# Remove empty strings caused by leading/trailing spaces
words = [w for w in words if w != '']
total_words += len(words)

print("Total characters (including spaces):", total_chars)
print("Total alphabets :", total_alpha)
print("Total digits :", total_digits)
print("Total special symbols :", total_special)
print("Total words :", total_words)
```

Sample Run:
```
Enter lines of text (press Enter on empty line to stop):
Hello World 123!

Total characters (including spaces): 16
Total alphabets : 10
Total digits : 3
Total special symbols : 1
Total words : 3
```
2Write a user defined function to convert a string with more than one word into title case string where string is passed as parameter. (Title case means that the first letter of each word is capitalised)Show solution
Concept Used:
- Split the string into individual words using `split()`.
- Capitalise the first letter of each word using `capitalize()` (or manually using indexing).
- Join the words back using `join()`.

Program:

```python
def toTitleCase(sentence):
"""
Converts a string to title case.
Parameter: sentence (str) - input string
Returns : title-cased string
"""
words = sentence.split() # Split on whitespace
title_words = []
for word in words:
# Capitalise first letter, lowercase the rest
title_word = word[0].upper() + word[1:].lower()
title_words.append(title_word)
return ' '.join(title_words)

# --- Driver code ---
text = input("Enter a string: ")
result = toTitleCase(text)
print("Title Case String:", result)
```

Sample Run:
```
Enter a string: hello world from python
Title Case String: Hello World From Python
```

Note: Python also provides a built-in `str.title()` method, but the above function demonstrates the logic manually as expected in a board exam.
3Write a function deleteChar() which takes two parameters — one is a string and other is a character. The function should create a new string after deleting all occurrences of the character from the string and return the new string.Show solution
Concept Used:
- Traverse each character of the string.
- Build a new string by appending only those characters that are not equal to the given character.
- Return the new string.

Program:

```python
def deleteChar(string, char):
"""
Deletes all occurrences of 'char' from 'string'.
Parameters:
string (str) - original string
char (str) - character to be deleted
Returns:
new string with all occurrences of char removed
"""
new_string = "" # Start with an empty string
for ch in string:
if ch != char: # Keep character only if it is not the target
new_string += ch
return new_string

# --- Driver code ---
s = input("Enter a string : ")
c = input("Enter character to delete: ")
result = deleteChar(s, c)
print("String after deletion:", result)
```

Sample Run:
```
Enter a string : programming
Enter character to delete: g
String after deletion: prorammin
```
4Input a string having some digits. Write a function to return the sum of digits present in this string.Show solution
Concept Used:
- Traverse each character of the string.
- Use `isdigit()` to check whether a character is a digit.
- Convert the digit character to integer using `int()` and add it to a running sum.

Program:

```python
def sumOfDigits(string):
"""
Returns the sum of all digit characters in the string.
Parameter: string (str) - input string
Returns : integer sum of digits
"""
total = 0
for ch in string:
if ch.isdigit(): # Check if character is a digit
total += int(ch) # Convert to int and add
return total

# --- Driver code ---
s = input("Enter a string containing digits: ")
result = sumOfDigits(s)
print("Sum of digits in the string:", result)
```

Sample Run:
```
Enter a string containing digits: abc12d34
Sum of digits in the string: 10
```

Explanation: Digits are `1`, `2`, `3`, `4`; sum =1+2+3+4=10= 1 + 2 + 3 + 4 = 10.
5Write a function that takes a sentence as an input parameter where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then return the modified sentence.Show solution
Concept Used:
- Use the string `replace()` method to replace every space `' '` with a hyphen `'-'`.
- Alternatively, traverse the string character by character and build a new string.

Program:

```python
def replaceBlankWithHyphen(sentence):
"""
Replaces every space in the sentence with a hyphen '-'.
Parameter: sentence (str) - input sentence
Returns : modified string with hyphens in place of spaces
"""
modified = ""
for ch in sentence:
if ch == ' ': # If character is a space
modified += '-' # Replace with hyphen
else:
modified += ch # Keep the character as is
return modified

# --- Driver code ---
sentence = input("Enter a sentence: ")
result = replaceBlankWithHyphen(sentence)
print("Modified sentence:", result)
```

Sample Run:
```
Enter a sentence: Hello World from Python
Modified sentence: Hello-World-from-Python
```

Alternative one-liner using `replace()`:
```python
def replaceBlankWithHyphen(sentence):
return sentence.replace(' ', '-')
```
Both approaches give the same result.

Stuck on a step?

Ask Super Tutor AI to explain any solution on this page in a simpler way — free, 24x7.

Ask a Doubt Free

Frequently Asked Questions

What are the important topics in Strings for Bihar Board Class 11 Computer Science?
Strings covers several key topics that are frequently asked in Bihar Board Class 11 board exams. Focus on the core concepts listed on this page and practise related questions to build confidence.
How to score full marks in Strings — Bihar Board Class 11 Computer Science?
Understand the core concepts first, then work through the 45 practice questions available for this chapter. Revise formulas and definitions regularly, and use flashcards for quick recall before the exam.
Where can I get free NCERT Solutions for Strings Class 11 Computer Science?
This page has free step-by-step NCERT Solutions for every exercise question in Strings (Bihar Board Class 11 Computer Science) — written the way examiners award marks: given, formula, working, answer.

Sources & Official References

Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.

For serious students

Get the full Strings chapter — for free.

Quizzes, flashcards, AI doubt-solver and a step-by-step study plan for Bihar Board Class 11 Computer Science.