Lesson 17

Strings

Strings

In this lesson: you will work with text: take letters, change text to capital or small letters, and split it into words.

The whole lesson on one page

Strings

In this lesson: you will work with text: take letters, change text to capital or small letters, and split it into words.

A string is a list of letters

A string is like a list: it has a length and indexes:

1тағ калима = "китоб";
2чоп(калима.дарозӣ);
3чоп(калима[0]);
4чоп(калима[калима.дарозӣ - 1]);
5барои (тағ ҳарф аз калима) {
6 чоп(ҳарф);
7}

You cannot change a letter of a string; you have to build a new string.

Building a string

1тағ ном = хондан();
2тағ синну = хонданиРақам();
3чоп("Салом, " + ном + "!");
4чоп(`${ном} ${синну} сола аст.`);
Input
Зарина
13

Between backticks … (a template string), you can put a value into the text with ${…}.

String methods

MethodMeaningExampleResult
калон()capital letters"салом".калон()"САЛОМ"
хурд()small letters"САЛОМ".хурд()"салом"
дорад(х)is х in the string?"Душанбе".дорад("шан")дуруст
тозаКардан()remove spaces at the edges" ҳа ".тозаКардан()"ҳа"
ҷудокунӣ(" ")split into parts"ман ту ӯ".ҷудокунӣ(" ")["ман", "ту", "ӯ"]
такрор(н)repeat н times"ҳа".такрор(3)"ҳаҳаҳа"
1тағ ҷумла = хондан();
2тағ калимаҳо = ҷумла.ҷудокунӣ(" ");
3чоп("Калимаҳо:", калимаҳо.дарозӣ);
4чоп(ҷумла.калон());
Input
ман барномасозиро дӯст медорам

Task: Length of a name

Read a name and print the number of letters in it.

Input: One line: a name.

Output: The number of letters.

Task: The letter "а"

Read a line and print how many times the lowercase letter а appears in it.

Input: One line.

Output: The count.

Task: Palindrome

Read a word. If it reads the same from the end (for example, нон, "bread"), print Ҳа ("Yes"), otherwise Не ("No").

Input: One word.

Output: Ҳа or Не

Task: Words

Read a sentence (the words are separated by one space) and print the number of words.

Input: One line.

Output: The number of words.