Home Common Problem Is a string a linear list with special data objects and operations?

Is a string a linear list with special data objects and operations?

Feb 03, 2021 am 11:14 AM
data structure

Yes, string is a linear list structure with special data objects and operations. The string mentioned in the data structure is a string; the characters in the string have a "one-to-one" logical relationship, so strictly speaking, the string storage structure is a linear storage structure.

Is a string a linear list with special data objects and operations?

The operating environment of this tutorial: Windows 7 system, Dell G3 computer.

The string mentioned in the data structure, that is, a string, is a whole composed of n characters (n >= 0). These n characters can be composed of letters, numbers, or other characters.

In the data structure, strings must be stored in a separate storage structure, which is called a string storage structure.

Strictly speaking, the string storage structure is also a linear storage structure, because the characters in the string also have a "one-to-one" logical relationship. However, unlike the linear storage structure we learned before, the string structure is only used to store character type data.

Special strings

  • Empty string: A string containing zero characters. For example: S = "" (nothing in double quotes), usually expressed directly as Ø.

  • Space string: A string containing only spaces. Note that it is different from the empty string. There is content in the space string, but it contains spaces, and the space string can contain multiple spaces. For example, a = " " (contains 3 spaces).

  • Substring and main string: A string composed of any consecutive characters in the string is called a substring of the string, and the string containing the substring is called the main string.

For example: a = "BEI", b = "BEIJING", c = "BJINGEI". For strings a and b, since b contains the continuous string a,

, it can be said that a is a substring of b, and b is the main string of a; and for c and a, although c also contains all the characters of a, but not consecutive "BEI", so the string c has no relationship with a.

The position of substring in the main string: for string a = "BEI", the position of the first character 'B' in string b is 1, so the position of substring a in main string b = The position in "BEIJING" is 1.

The position of the substring in the main string is different from the storage position of the characters in the array. The position of the substring in the main string starts from 1.

Standard for equality of two strings: If the string values ​​of two strings are exactly the same, then the two strings are equal.

There are three storage structures for string storage

There are three structures for storing strings:

1 Fixed-length sequential storage;

2 Heap allocation storage;

3 Block chain storage.

Fixed-length sequential storage

Use a fixed-length array (i.e., static array) to store strings.

For example: char a[7] = "abcdfg";

When storing a string in this way, you need to estimate the length of the string and apply for enough storage space in advance. If the target string exceeds the length requested by the array, the excess part will be automatically discarded (called "truncation").

For example: char a[3] = "abcdfg";//In fact, only "abc" is stored in the array, and the following ones are truncated. Heap allocated storage

Uses dynamic array to store string

In C language, there is a free storage area called "heap", using the malloc function and Free function management, malloc function is responsible for applying for space, and free function is responsible for releasing space.

For example:

1

char * a = (char*)malloc(5*sizeof(char));//创建 a 数组,动态申请5个 char 类型数据的存储空间

Copy after login

The advantage of using heap allocation storage is that when it is found that the applied space is not enough, you can re-apply for larger storage space through the realloc() function.

1

例如:a = (char*)realloc(a, 10*sizeof(char));//前一个参数指申请空间的对象;第二个参数,重新申请空间的大小

Copy after login

The storage space applied for using the malloc function will not be released automatically, and the programmer needs to call the free() function to release it manually. If it is not released manually, it will be recycled by the operating system when the program execution is completely completed.

1

例如:free(a);//释放动态数组a申请的空间

Copy after login

To give a complete example, the connection strings "abc" and "defg" become "abcdefg";

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main()

{

    char * a1=NULL;

    char * a2=NULL;

     

    a1=(char*)malloc(3*sizeof(char));

    strcpy(a1, "abc");//将字符串“abc”复制给a1

     

    a2=(char*)malloc(3*sizeof(char));

    strcpy(a2, "defg");

     

    int lengthA1=strlen(a1);

    int lengthA2=strlen(a2);

    if (lengthA1<lengthA1+lengthA2) {

        a1=(char*)realloc(a1, (lengthA1+lengthA2)*sizeof(char));

    }

    int i;

    for (i=lengthA1; i<lengthA1+lengthA2; i++) {

        a1[i]=a2[i-lengthA1];

    }

    printf("%s",a1);

     

    free(a1);

    free(a2);

    return 0;

}

Copy after login

Is a string a linear list with special data objects and operations?

Note: In the program, When we assigned values ​​to a1 and a2, we used the strcpy copy function. You cannot use it directly here: a1 = "abc".

If you do this, the program will compile with an error, telling you that space without malloc cannot be freed.

The reason is: The strcpy function copies the string to the applied storage space, while direct assignment means the string is stored in another memory space (itself a constant, placed in the constant area),

The pointing of pointers a1 and a2 has been changed. In other words, although the storage space dynamically applied for before was applied for, it was lost before it was used.

Block chain storage

Block chain storage actually borrows the storage structure of a linked list to store strings. Under normal circumstances, it is enough to use a single linked list, and there is no need to add a head node.

When building a linked list, each node can store one character or multiple characters.

Is a string a linear list with special data objects and operations?

链表中最后一个结点的数据域不一定全被串值占满,通常会补上 “#” 或者其他特殊的字符和字符串中的字符区分开。

每个结点设置字符数量的多少和存储的串的长度、可以占用的存储空间以及程序实现的功能相关。

如果串包含数据量很大,但是可用的存储空间有限,那么就需要提高空间利用率,相应地减少结点数量(因为多一个节点,就多申请一个指针域的空间)。

而如果程序中需要大量地插入或者删除数据,如果每个节点包含的字符过多,操作字符就会变得很麻烦,为实现功能增加了障碍。

总结

在平时编写程序,经常会用到例如:char *a = ”abcd”;这种方式表示字符串,和上面三种存储方式最主要的区别是:这种方式用于表示常量字符串,只能使用,不能对字符串内容做修改(否则程序运行出错);而以上三种方式都可以对字符串进行删改的操作。

例如:

1

2

3

4

5

6

#include <stdio.h>

int main() {

    char* a="abcd";

    a[1]=&#39;b&#39;;

    return 0;

}

Copy after login

程序编译可以通过,运行失败,改成下面堆分配存储的方式就对了:

1

2

3

4

5

6

7

8

9

10

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main() {

    char * a=(char*)malloc(4*sizeof(char));

    strcpy(a, "abcd");

    a[1]=&#39;e&#39;;

    printf("%s",a);

    return 0;

}

Copy after login

Is a string a linear list with special data objects and operations?

三种存储表示方式中,最常用的是堆分配存储,因为它在定长存储的基础上通过使用动态数组,避免了在操作串时可能因为申请存储空间的不足而丢失字符数据;和块链存储方式相比,结构相对简单,更容易操作。

更多计算机编程相关知识,请访问:编程视频!!

The above is the detailed content of Is a string a linear list with special data objects and operations?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Compare complex data structures using Java function comparison Compare complex data structures using Java function comparison Apr 19, 2024 pm 10:24 PM

When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

In-depth understanding of reference types in Go language In-depth understanding of reference types in Go language Feb 21, 2024 pm 11:36 PM

Reference types are a special data type in the Go language. Their values ​​do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure Jun 03, 2024 am 09:58 AM

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Feb 23, 2024 am 10:49 AM

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

PHP SPL data structures: Inject speed and flexibility into your projects PHP SPL data structures: Inject speed and flexibility into your projects Feb 19, 2024 pm 11:00 PM

Overview of the PHPSPL Data Structure Library The PHPSPL (Standard PHP Library) data structure library contains a set of classes and interfaces for storing and manipulating various data structures. These data structures include arrays, linked lists, stacks, queues, and sets, each of which provides a specific set of methods and properties for manipulating data. Arrays In PHP, an array is an ordered collection that stores a sequence of elements. The SPL array class provides enhanced functions for native PHP arrays, including sorting, filtering, and mapping. Here is an example of using the SPL array class: useSplArrayObject;$array=newArrayObject(["foo","bar","baz"]);$array

Hash table-based data structure optimizes PHP array intersection and union calculations Hash table-based data structure optimizes PHP array intersection and union calculations May 02, 2024 pm 12:06 PM

The hash table can be used to optimize PHP array intersection and union calculations, reducing the time complexity from O(n*m) to O(n+m). The specific steps are as follows: Use a hash table to map the elements of the first array to a Boolean value to quickly find whether the element in the second array exists and improve the efficiency of intersection calculation. Use a hash table to mark the elements of the first array as existing, and then add the elements of the second array one by one, ignoring existing elements to improve the efficiency of union calculations.

Learn the secrets of Go language data structures in depth Learn the secrets of Go language data structures in depth Mar 29, 2024 pm 12:42 PM

In-depth study of the mysteries of Go language data structure requires specific code examples. As a concise and efficient programming language, Go language also shows its unique charm in processing data structures. Data structure is a basic concept in computer science, which aims to organize and manage data so that it can be accessed and manipulated more efficiently. By in-depth learning the mysteries of Go language data structure, we can better understand how data is stored and operated, thereby improving programming efficiency and code quality. 1. Array Array is one of the simplest data structures