Как в программировании работают строки? Какие операции можно над ними выполнять?

Строка — это последовательность символов. Она используется для хранения и обработки текстовой информации.

Примеры строк:

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); // 5
const word = 'hello';
console.log(word.length); // 5
package 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)) # 5

2. Доступ к символу по индексу

const word = 'hello';
console.log(word[0]); // h
console.log(word[1]); // e
const word = 'hello';
console.log(word[0]); // h
console.log(word[1]); // e
package 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 + ' ' + lastName

4. Получение подстроки

const text = 'programming';
console.log(text.slice(0, 7)); // program
const text = 'programming';
console.log(text.slice(0, 7)); // program
package 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]) # program

5. Поиск в строке

const text = 'Hello, world!';
console.log(text.includes('world')); // true
console.log(text.indexOf('o'));      // 4
const text = 'Hello, world!';
console.log(text.includes('world')); // true
console.log(text.indexOf('o'));      // 4
package 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')) # 4

6. Замена части строки

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 world
const words = ['Hello', 'world'];
const sentence = words.join(' ');
console.log(sentence); // Hello world
package 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 world

9. Изменение регистра

const text = 'Hello';
console.log(text.toUpperCase()); // HELLO
console.log(text.toLowerCase()); // hello
const text = 'Hello';
console.log(text.toUpperCase()); // HELLO
console.log(text.toLowerCase()); // hello
package 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()) # hello

10. Сравнение строк

Строки можно сравнивать:

console.log('apple' === 'apple'); // true
console.log('apple' < 'banana');  // true
console.log('apple' === 'apple'); // true
console.log('apple' < 'banana');  // true
package 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 не всегда очевидна при обычном подсчете через length.

Где используются строки?

Строки применяются:

Вывод

Строка — это последовательность символов. Над строками можно выполнять множество операций: соединение, поиск, сравнение, замену, получение подстрок, изменение регистра, разделение и форматирование.

Источники

  • Горбатов В.А., Горбатов А.В., Горбатова М.В. Дискретная математика: Учебник для студентов втузов. - М.: АСТ, 2014. - 448 с.
  • Горбатов В.А., Горбатов А.В., Горбатова М.В. Теория автоматов: учебник для втузов. - М.: АСТ, 2008. - 559 с.
  • Кузнецов О. П. Дискретная математика для инженера. - Санкт-Петербург [и др.]: Лань, 2009.
  • Содержание курса лекций «Языки программирования». Кафедра алгоритмических языков ВМК МГУ, 2018.
  • Босова Л.Л. Информатика. Базовый курс: учебник для 10-11 классов. - М.: БИНОМ. Лаборатория знаний, 2021.
  • Гладкий Ю.Н. Информатика и информационные технологии: учеб. пособие. - М.: КноРус, 2020.