Strings & Text Processing MCQs for NSCT

By the NSCT Exam Editorial Team · Updated 2026-11-24 · Facts checked against official sources on 2026-11-24

Strings and text processing covers how C++, Java and Python store text, which string methods you use to search, split and change it, why strings are immutable in Java and Python, and how to format output. It is topic 7 of the Programming (C++/Java/Python) area, which carries 10% of the NSCT according to HEC's Areas of Competencies. In 2026 candidates averaged 47.8% in Programming, per the HEC NSCT report and APP.

Most string questions are output questions, so they build on data types and operators: a single character in the wrong place changes the answer.

How each language stores text

C C++ Java Python 3
Type char array std::string String str
Mutable? Yes Yes No No
End of text '\0' terminator Stored length Stored length Stored length
Content equality strcmp(a, b) == 0 a == b a.equals(b) a == b

A C string "hello" takes 6 bytes because of the terminating null character. Exam angle: in Java, == on two String objects compares references (whether they are the same object), not characters, so always use equals().

String methods

A string method is a built-in operation on a string object. The ones that appear most often:

Task Python Java
Length len(s) s.length()
Character at i s[i] s.charAt(i)
Part of the string s[2:5] s.substring(2, 5)
Find s.find("x") (−1 if missing) s.indexOf("x") (−1 if missing)
Split and join s.split(","), ",".join(parts) s.split(","), String.join(",", parts)
Change case s.upper(), s.lower() s.toUpperCase(), s.toLowerCase()

Slices and substring are half-open: the end index is excluded. So "network"[0:3] is "net", and s[::-1] reverses a Python string. Exam angle: split(",") keeps empty strings between adjacent commas, while Python's split() with no argument drops them.

Immutability

An immutable object cannot change after it is created. Java String and Python str are immutable; every "change" returns a new string.

name = "ali"
name.upper()        # result thrown away
print(name)         # ali
name = name.upper()
print(name)         # ALI

Immutability makes strings safe to share and to use as dictionary keys, and it lets Java keep a string pool of literals. The cost is that building text with += in a loop copies the whole string each time, which is O(n²) overall. Use StringBuilder in Java or "".join(parts) in Python. C++ std::string is mutable, so s[0] = 'b' is legal there. Exam angle: "the method ran but the string did not change" nearly always means the return value was not assigned.

Formatting

Formatting turns values into text with a set width, precision or alignment.

pi, n = 3.14159, 42
print(f"{pi:.3f}|{n:5d}|{n:<5d}|{n:05d}")  # 3.142|   42|42   |00042

Java's String.format("%.3f", pi) and C's printf use the same % codes: d for integers, f for floating point, s for strings, with width before the dot and precision after it. Exam angle: count the padding spaces exactly; width is the total field size, not the number of spaces added.

Text processing basics

Text processing means cleaning and analysing text: trimming whitespace, normalising case, counting words or extracting numbers. A regular expression (regex) is a pattern language for this; re.findall(r"[A-Z]+", "NSCT 2026 HEC") returns ['NSCT', 'HEC']. Characters are numbers underneath: ord('a') is 97, so comparisons are by code point and every capital letter sorts before every lowercase one.

Common traps

Worked examples

Understanding. Which Java class should you use to reverse a string in place and append to it many times? Answer: StringBuilder. It is mutable and has append() and reverse(); String would create a new object for every change.

Application. What does print("data,science,,ai".split(",")[2] == "") print in Python? Answer: True. The two adjacent commas create an empty string, so the list is ['data', 'science', '', 'ai'] and index 2 is ''.

Analysis. A Python function returns word.strip().lower() == "yes". A user types " Yes\n", and it still returns True. A colleague says strip() is unnecessary because lower() handles case. Who is right? Answer: the function is right as written. lower() changes case only; strip() removes the leading space and the trailing newline. Without strip(), " yes\n" == "yes" is False.

Practise

The quiz below has 100 Strings & Text Processing questions, which you can filter by tier and difficulty.

Practise: 100 questions

Interactive quiz loading. The first 10 questions are shown below.

  1. In Python, what happens when this code runs?

    s = "cat"
    s[0] = "b"
    1. An IndexError is raised because index 0 is read-only
    2. s becomes "bat"
    3. A TypeError is raised because str objects do not support item assignment
    4. A new string "bat" is created and s still holds "cat"
    Show answer

    Answer: C. A TypeError is raised because str objects do not support item assignment

    Python strings are immutable, so assigning to s[0] raises TypeError: 'str' object does not support item assignment. To get "bat" you build a new string, for example s = "b" + s[1:].

  2. In Java, which of these classes gives you a mutable sequence of characters?

    1. Integer
    2. String
    3. Character
    4. StringBuilder
    Show answer

    Answer: D. StringBuilder

    StringBuilder (and the synchronised StringBuffer) can be changed in place with append, insert and reverse. String objects are immutable, and Character and Integer are immutable wrapper classes.

  3. In C, how does a function such as strlen() know where a character-array string ends?

    1. It uses the declared size of the array
    2. It stops at the null character '\0'
    3. It stops at the first space character
    4. It reads a length field stored before the first character
    Show answer

    Answer: B. It stops at the null character '\0'

    A C string is a char array terminated by the null character '\0'. strlen() counts characters until it reaches that terminator; it has no access to the array's declared size.

  4. In Java, which expression compares the characters of two String objects a and b rather than their references?

    1. a == b
    2. a.equals(b)
    3. a.compareTo(b) == 1
    4. a.hashCode() == b.hashCode()
    Show answer

    Answer: B. a.equals(b)

    equals() compares content. == on objects compares references, so two separate String objects with the same text can give false. Equal hash codes do not prove equality, and compareTo returns 0 (not 1) for equal strings.

  5. What does Python's str.strip() remove when it is called with no arguments?

    1. Whitespace at both the start and the end of the string
    2. Only leading spaces
    3. All whitespace, including spaces between words
    4. Only trailing newline characters
    Show answer

    Answer: A. Whitespace at both the start and the end of the string

    With no argument, strip() removes leading and trailing whitespace (spaces, tabs, newlines). It never touches characters inside the string; lstrip() and rstrip() trim one side only.

  6. Why is repeated s = s + piece inside a long Java loop considered inefficient?

    1. The Java compiler rejects + on strings inside loops
    2. String concatenation is not allowed with variables, only with literals
    3. Each + forces an immediate garbage collection
    4. Each iteration creates a new String and copies all existing characters into it
    Show answer

    Answer: D. Each iteration creates a new String and copies all existing characters into it

    Because String is immutable, every + builds a new object and copies the old contents, so building n characters this way copies O(n^2) characters in total. A single StringBuilder appends in amortised constant time per character.

  7. Which statement about std::string in C++ is correct?

    1. It is immutable like Java's String
    2. It is mutable: s[0] = 'b' changes the string in place
    3. It cannot be compared with the == operator
    4. It must always be terminated manually with '\0'
    Show answer

    Answer: B. It is mutable: s[0] = 'b' changes the string in place

    std::string is a mutable class: you can assign to s[i], append with += and erase characters. It manages its own length and memory, and operator== compares contents. C-style char arrays are the ones that need '\0'.

  8. Which Python string literal is an f-string that inserts the value of the variable name?

    1. f"Hello {name}"
    2. b"Hello {name}"
    3. r"Hello {name}"
    4. "Hello {name}"
    Show answer

    Answer: A. f"Hello {name}"

    The f prefix (Python 3.6+) evaluates expressions inside braces at run time. Without it the braces stay as literal text; r marks a raw string and b a bytes literal.

  9. In Java, String a = "hi"; String b = "hi"; Why does a == b give true?

    1. == always compares string contents in Java
    2. The compiler converts == into equals() for strings
    3. String literals with the same content are interned, so both variables refer to one pooled object
    4. Both variables are primitive values, not objects
    Show answer

    Answer: C. String literals with the same content are interned, so both variables refer to one pooled object

    The Java Language Specification requires string literals to be interned in the string pool, so identical literals share one object and == compares equal references. Strings built at run time (for example with new String or concatenation of variables) are separate objects.

  10. In Python, what is the difference between s.find(sub) and s.index(sub) when sub is not in s?

    1. find raises ValueError, while index returns -1
    2. find returns -1, while index raises ValueError
    3. Both return None
    4. Both return -1
    Show answer

    Answer: B. find returns -1, while index raises ValueError

    find() signals a missing substring with -1. index() behaves the same when the substring is present but raises ValueError when it is not, so it needs a try/except.

FAQs

Are strings mutable in C++?

Yes. std::string in C++ is mutable: you can assign to s[i], call append() or +=, and erase characters in place. Only Java's String and Python's str are immutable among the three languages. A C-style char array is also mutable, but a string literal such as "hello" must not be modified.

What is the difference between == and equals() in Java?

== checks whether two references point to the same object. equals() checks whether two strings contain the same characters. Literals with the same text share one pooled object, so == can appear to work in small tests, then fail for strings read from input or built at run time.

Why is StringBuilder faster than + in a loop?

Each + on a Java String creates a new object and copies all existing characters, so n appends copy about n²/2 characters. StringBuilder keeps a resizable buffer and adds characters to the end, so the same loop does linear work. Python's equivalent is collecting pieces in a list and calling "".join() once.

How do I format a number to two decimal places?

In Python write f"{x:.2f}" or "{:.2f}".format(x). In Java use String.format("%.2f", x) or System.out.printf("%.2f", x). In C++ use std::fixed << std::setprecision(2) from <iomanip>. All three round to two digits after the decimal point.

Next step

Continue with Arrays & Collections MCQs, go back to the Programming hub, or try a timed NSCT mock test.