Как в программировании работают строки? Какие операции можно над ними выполнять?
Строка — это последовательность символов. Она используется для хранения и обработки текстовой информации.
Примеры строк:
const name = 'Даниил';
const message = 'Hello, world!';
const empty = '';const name = 'Даниил';
const message = 'Hello, world!';
const empty = '';package main
func main() {
name := "Даниил"
message := "Hello, world!"
empty := ""
}public class Example {
public static void main(String[] args) {
var name = "Даниил";
var message = "Hello, world!";
var empty = "";
}
}name = 'Даниил'
message = 'Hello, world!'
empty = ''Строка может быть пустой, то есть не содержать ни одного символа.
Как строки хранятся?
В компьютере строка хранится как последовательность кодов символов. Каждый символ имеет числовое представление в определенной кодировке.
В разных языках строки могут быть:
- изменяемыми;
- неизменяемыми.
Например, в JavaScript и TypeScript строки являются неизменяемыми. Это значит, что при изменении строки фактически создается новая строка.
let text = 'cat';
text = text + 's'; // создается новая строка 'cats'let text = 'cat';
text = text + 's'; // создается новая строка 'cats'package main
func main() {
text := "cat"
text = text + "s" // создается новая строка "cats"
}public class Example {
public static void main(String[] args) {
var text = "cat";
text = text + "s"; // создается новая строка "cats"
}
}text = 'cat'
text = text + 's' # создается новая строка 'cats'Основные операции над строками
1. Определение длины строки
const word = 'hello';
console.log(word.length); // 5const word = 'hello';
console.log(word.length); // 5package main
import "fmt"
func main() {
word := "hello"
fmt.Println(len(word)) // 5
}public class Example {
public static void main(String[] args) {
var word = "hello";
System.out.println(word.length()); // 5
}
}word = 'hello'
print(len(word)) # 52. Доступ к символу по индексу
const word = 'hello';
console.log(word[0]); // h
console.log(word[1]); // econst word = 'hello';
console.log(word[0]); // h
console.log(word[1]); // epackage main
import "fmt"
func main() {
word := "hello"
fmt.Println(string(word[0])) // h
fmt.Println(string(word[1])) // e
}public class Example {
public static void main(String[] args) {
var word = "hello";
System.out.println(word.charAt(0)); // h
System.out.println(word.charAt(1)); // e
}
}word = 'hello'
print(word[0]) # h
print(word[1]) # eОбычно индексация начинается с нуля.
3. Конкатенация
Конкатенация — это соединение строк.
const firstName = 'Иван';
const lastName = 'Петров';
const fullName = firstName + ' ' + lastName;const firstName = 'Иван';
const lastName = 'Петров';
const fullName = firstName + ' ' + lastName;package main
func main() {
firstName := "Иван"
lastName := "Петров"
fullName := firstName + " " + lastName
}public class Example {
public static void main(String[] args) {
var firstName = "Иван";
var lastName = "Петров";
var fullName = firstName + " " + lastName;
}
}firstName = 'Иван'
lastName = 'Петров'
fullName = firstName + ' ' + lastName4. Получение подстроки
const text = 'programming';
console.log(text.slice(0, 7)); // programconst text = 'programming';
console.log(text.slice(0, 7)); // programpackage main
import "fmt"
func main() {
text := "programming"
fmt.Println(text[0:7]) // program
}public class Example {
public static void main(String[] args) {
var text = "programming";
System.out.println(text.substring(0, 7)); // program
}
}text = 'programming'
print(text[0:7]) # program5. Поиск в строке
const text = 'Hello, world!';
console.log(text.includes('world')); // true
console.log(text.indexOf('o')); // 4const text = 'Hello, world!';
console.log(text.includes('world')); // true
console.log(text.indexOf('o')); // 4package main
import (
"fmt"
"strings"
)
func main() {
text := "Hello, world!"
fmt.Println(strings.Contains(text, "world")) // true
fmt.Println(strings.Index(text, "o")) // 4
}public class Example {
public static void main(String[] args) {
var text = "Hello, world!";
System.out.println(text.contains("world")); // true
System.out.println(text.indexOf("o")); // 4
}
}text = 'Hello, world!'
print('world' in text) # True
print(text.find('o')) # 46. Замена части строки
const text = 'Hello, world!';
const result = text.replace('world', 'student');
console.log(result); // Hello, student!const text = 'Hello, world!';
const result = text.replace('world', 'student');
console.log(result); // Hello, student!package main
import (
"fmt"
"strings"
)
func main() {
text := "Hello, world!"
result := strings.ReplaceAll(text, "world", "student")
fmt.Println(result) // Hello, student!
}public class Example {
public static void main(String[] args) {
var text = "Hello, world!";
var result = text.replace("world", "student");
System.out.println(result); // Hello, student!
}
}text = 'Hello, world!'
result = text.replace('world', 'student')
print(result) # Hello, student!7. Разделение строки
const data = 'apple,banana,orange';
const fruits = data.split(',');
console.log(fruits); // ['apple', 'banana', 'orange']const data = 'apple,banana,orange';
const fruits = data.split(',');
console.log(fruits); // ['apple', 'banana', 'orange']package main
import (
"fmt"
"strings"
)
func main() {
data := "apple,banana,orange"
fruits := strings.Split(data, ",")
fmt.Println(fruits) // [apple banana orange]
}public class Example {
public static void main(String[] args) {
var data = "apple,banana,orange";
var fruits = data.split(",");
System.out.println(java.util.Arrays.toString(fruits)); // [apple, banana, orange]
}
}data = 'apple,banana,orange'
fruits = data.split(',')
print(fruits) # ['apple', 'banana', 'orange']8. Объединение массива строк
const words = ['Hello', 'world'];
const sentence = words.join(' ');
console.log(sentence); // Hello worldconst words = ['Hello', 'world'];
const sentence = words.join(' ');
console.log(sentence); // Hello worldpackage main
import (
"fmt"
"strings"
)
func main() {
words := []string{"Hello", "world"}
sentence := strings.Join(words, " ")
fmt.Println(sentence) // Hello world
}public class Example {
public static void main(String[] args) {
var words = new String[] {"Hello", "world"};
var sentence = String.join(" ", words);
System.out.println(sentence); // Hello world
}
}words = ['Hello', 'world']
sentence = ' '.join(words)
print(sentence) # Hello world9. Изменение регистра
const text = 'Hello';
console.log(text.toUpperCase()); // HELLO
console.log(text.toLowerCase()); // helloconst text = 'Hello';
console.log(text.toUpperCase()); // HELLO
console.log(text.toLowerCase()); // hellopackage main
import (
"fmt"
"strings"
)
func main() {
text := "Hello"
fmt.Println(strings.ToUpper(text)) // HELLO
fmt.Println(strings.ToLower(text)) // hello
}public class Example {
public static void main(String[] args) {
var text = "Hello";
System.out.println(text.toUpperCase()); // HELLO
System.out.println(text.toLowerCase()); // hello
}
}text = 'Hello'
print(text.upper()) # HELLO
print(text.lower()) # hello10. Сравнение строк
Строки можно сравнивать:
console.log('apple' === 'apple'); // true
console.log('apple' < 'banana'); // trueconsole.log('apple' === 'apple'); // true
console.log('apple' < 'banana'); // truepackage main
import "fmt"
func main() {
fmt.Println("apple" == "apple") // true
fmt.Println("apple" < "banana") // true
}public class Example {
public static void main(String[] args) {
System.out.println("apple".equals("apple")); // true
System.out.println("apple".compareTo("banana") < 0); // true
}
}print('apple' == 'apple') # True
print('apple' < 'banana') # TrueОбычно сравнение выполняется лексикографически, то есть примерно как в словаре, но с учетом кодов символов.
Особенности работы со строками
При работе со строками важно учитывать:
- кодировку;
- регистр букв;
- пробелы;
- специальные символы;
- символы разных языков;
- emoji и составные Unicode-символы.
Например, длина строки с emoji не всегда очевидна при обычном подсчете через length.
Где используются строки?
Строки применяются:
- для хранения имен, адресов, сообщений;
- при работе с файлами;
- при вводе и выводе данных;
- в базах данных;
- в веб-разработке;
- при обработке JSON, HTML, CSS, SQL-запросов;
- в поиске и анализе текста.
Вывод
Строка — это последовательность символов. Над строками можно выполнять множество операций: соединение, поиск, сравнение, замену, получение подстрок, изменение регистра, разделение и форматирование.
Источники
- Горбатов В.А., Горбатов А.В., Горбатова М.В. Дискретная математика: Учебник для студентов втузов. - М.: АСТ, 2014. - 448 с.
- Горбатов В.А., Горбатов А.В., Горбатова М.В. Теория автоматов: учебник для втузов. - М.: АСТ, 2008. - 559 с.
- Кузнецов О. П. Дискретная математика для инженера. - Санкт-Петербург [и др.]: Лань, 2009.
- Содержание курса лекций «Языки программирования». Кафедра алгоритмических языков ВМК МГУ, 2018.
- Босова Л.Л. Информатика. Базовый курс: учебник для 10-11 классов. - М.: БИНОМ. Лаборатория знаний, 2021.
- Гладкий Ю.Н. Информатика и информационные технологии: учеб. пособие. - М.: КноРус, 2020.