search
HomeBackend DevelopmentC++Extract substrings between any pair of delimiters

Extract substrings between any pair of delimiters

分隔符是将字符串与其他字符分开的字符,例如在我们日常阅读活动中的句子中,我们通过空格分隔出不同的单词。在数学和正则表达式中,我们使用()括号作为主要的分隔符。

子字符串及其操作的概念在编程中非常重要,特别是在用于编写编译器和汇编器的C语言中。在字符串中识别定界符,并将起始定界符后的字符复制到另一个变量中,直到结束定界符。

== 和 != 运算符可用于比较字符串中的字符和用户指定的分隔符字符。

使用scanf()函数从用户接受一个字符串,所以空格不能作为字符串的一部分。如果使用puts()或其他函数或方法,可能会得到一个高级版本。

该程序使用数组和字符串处理的基本概念,而不使用头文件中可用的任何字符串函数。可以使用字符串比较、字符串复制函数,但作为简单逻辑的练习,该程序是使用非常基本的逻辑完成的。

Methods Used

的中文翻译为:

使用的方法

方法一:使用 substring()

方法2:使用函数

两种方法各有其优点。方法1是一种直接的解决方案,帮助用户理解字符串操作的过程,而方法2通过使用函数促进更好的软件设计原则和可维护性。

语法

在 C 编程语言中提取任意一对分隔符之间的子字符串是一项常见的编程任务。提取子串的方法可以根据具体的问题要求和约束而变化。尽管如此,一种广泛使用的技术是利用 C 标准库中的 strtok() 函数。该函数用于根据指定的分隔符将字符串分解为一系列标记。该函数将原始字符串和分隔符作为输入,并返回指向字符串中找到的第一个标记的指针。要提取所有子字符串,可以使用空指针作为第一个参数重复调用该函数以获得后续标记。字符串的结尾由 strtok() 函数返回的空指针指示。

char *strtok(char *str, const char *delim);

算法

步骤 1 - 声明 str1,str2,delim1,delim2 初始化为 null。

第 2 步 - 声明整型变量 len、n、I、subs

步骤 3 - 从控制台接收 str1、delim1 和 delim2

第 4 步 - 检查长度并将其存储在 len

步骤 5 - 当 n

第 6 步 - 如果是,则 subs=n,打破循环

步骤 7 − 当 str1[subs] != delim2 时,使 n=0

第 8 步 - 将 delim1 后的 str1 复制到 str2,str2[n] = str1[subs],递增 n 和 subs

步骤 9 - 打印 str2,其中输入字符串减号 ()。

方法一:使用substring()

对于字符串的简单逐步数组操作的实现具有几个优点。它直观且易于理解,这对于初学者或正在学习编程的人来说是有益的。这种方法允许用户看到程序用于操作字符串的确切过程。然而,正如前面提到的,这种方法有一些限制,例如不接受带有空格的字符串,并且将长度限制为20个字符。使用gets方法,您可以克服字符串大小的限制,但值得注意的是,由于潜在的缓冲区溢出和安全风险,gets方法已被弃用。

Example

的中文翻译为:

示例

这段代码构成了一个软件,它基于两个分隔符提取字符串的一部分。第一个分隔符指定了子字符串的开始,第二个分隔符定义了其结束。输入字符串存储在str1变量中,两个分隔符定义为delim1和delim2变量。提取的子字符串保存在str2变量中。程序首先使用第一个分隔符识别子字符串的起始位置,然后通过计算从起始位置到第二个分隔符定义的结束位置的字符数量来计算其长度。然后调用Substring函数从原始字符串中提取子字符串并将其存储在str2变量中。提取的子字符串然后显示在屏幕上。

#include <stdio.h>
#include <string.h>

void Substring(char *str2, const char *str1, int start, int n) {
   strncpy(str2, str1 + start, n);
}
int main() {
   // Predefined input values
   char str1[] = "Hello[world]!";
   char delim1 = '[';
   char delim2 = ']';

   char str2[100];
   int len1 = strlen(str1);
   int start, subs, n = 0;

   // Getting the position of substring based on delimiter
   while (n < len1) {
      if (str1[n] == delim1) {
         subs = n;
         break;
      }
      n++;
   }
   start = n;

   // Getting the length of substring
   if (str1[subs] == delim1) {
      n = 0;
      subs++;
      while (str1[subs] != delim2) {
         subs++;
         n++;
      }
      Substring(str2, str1, start + 1, n);
   }
   // Adding null character at the end
   str2[n] = '\0';
   printf("<span>\</span>nSub string is %s", str2);

   return 0;
}

输出

Sub string is world 

方法二:函数

使用函数来实现程序可以提供更模块化和有组织的解决方案。它将代码分解为较小、可重用的部分,可以独立进行测试和调试。这种方法促进了更好的软件设计原则和代码可读性。通过创建函数,您还可以轻松扩展程序的功能并提高其可维护性。

Example

的中文翻译为:

示例

此代码构成了一个 C 软件,用于提取定义的字符串的一部分。该字符串被声明为字符数组,并且分隔符在主函数中预先指定。 Getpos 函数用于确定字符串中第一个分隔符 (delim1) 的位置。 Copystr 函数用于将两个分隔符(delim1 和 delim2)之间的字符复制到新字符串中。原始字符串的长度是使用 string.h 库中的 strlen 函数计算的。然后使用 printf 函数将子字符串显示在屏幕上。

#include <stdio.h>
#include <string.h>

void Getpos(char *str1, int len1, char delim1, int *subs) {
   int n = 0;
   while (n < len1) {
      if (str1[n] == delim1) {
         *subs = n;
         break;
      }
      n++;
   }
}

void Copystr(char *str1, char *str2, char delim1, char delim2, int subs) {
   if (str1[subs] == delim1) {
      int n = 0;
      subs++;
      while (str1[subs] != delim2) {
         str2[n] = str1[subs];
         subs++;
         n++;
      }
   }
}

int main() {
   // Predefined input values
   char str1[] = "Hello[world]!";
   char delim1 = '[';
   char delim2 = ']';

   char str2[100];
   int len1, subs;

   len1 = strlen(str1);

   Getpos(str1, len1, delim1, &subs);
   Copystr(str1, str2, delim1, delim2, subs);

   str2[strlen(str2)] = '\0';

   printf("<span>\</span>nSub string is %s", str2);

   return 0;
} 

输出

Sub string is world

结论

C 中的字符串以字符的形式存储在内存中,字符串中的每个字符或字母都可以单独访问和处理。字符串的数组操作可以轻松地对字符串执行各种操作,如连接、反转,查找回文等等。这种灵活性使其在文件操作和最小内存使用方面非常有用。

The above is the detailed content of Extract substrings between any pair of delimiters. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C   in Specific Domains: Exploring Its StrongholdsC in Specific Domains: Exploring Its StrongholdsMay 06, 2025 am 12:08 AM

C is widely used in the fields of game development, embedded systems, financial transactions and scientific computing, due to its high performance and flexibility. 1) In game development, C is used for efficient graphics rendering and real-time computing. 2) In embedded systems, C's memory management and hardware control capabilities make it the first choice. 3) In the field of financial transactions, C's high performance meets the needs of real-time computing. 4) In scientific computing, C's efficient algorithm implementation and data processing capabilities are fully reflected.

Debunking the Myths: Is C   Really a Dead Language?Debunking the Myths: Is C Really a Dead Language?May 05, 2025 am 12:11 AM

C is not dead, but has flourished in many key areas: 1) game development, 2) system programming, 3) high-performance computing, 4) browsers and network applications, C is still the mainstream choice, showing its strong vitality and application scenarios.

C# vs. C  : A Comparative Analysis of Programming LanguagesC# vs. C : A Comparative Analysis of Programming LanguagesMay 04, 2025 am 12:03 AM

The main differences between C# and C are syntax, memory management and performance: 1) C# syntax is modern, supports lambda and LINQ, and C retains C features and supports templates. 2) C# automatically manages memory, C needs to be managed manually. 3) C performance is better than C#, but C# performance is also being optimized.

Building XML Applications with C  : Practical ExamplesBuilding XML Applications with C : Practical ExamplesMay 03, 2025 am 12:16 AM

You can use the TinyXML, Pugixml, or libxml2 libraries to process XML data in C. 1) Parse XML files: Use DOM or SAX methods, DOM is suitable for small files, and SAX is suitable for large files. 2) Generate XML file: convert the data structure into XML format and write to the file. Through these steps, XML data can be effectively managed and manipulated.

XML in C  : Handling Complex Data StructuresXML in C : Handling Complex Data StructuresMay 02, 2025 am 12:04 AM

Working with XML data structures in C can use the TinyXML or pugixml library. 1) Use the pugixml library to parse and generate XML files. 2) Handle complex nested XML elements, such as book information. 3) Optimize XML processing code, and it is recommended to use efficient libraries and streaming parsing. Through these steps, XML data can be processed efficiently.

C   and Performance: Where It Still DominatesC and Performance: Where It Still DominatesMay 01, 2025 am 12:14 AM

C still dominates performance optimization because its low-level memory management and efficient execution capabilities make it indispensable in game development, financial transaction systems and embedded systems. Specifically, it is manifested as: 1) In game development, C's low-level memory management and efficient execution capabilities make it the preferred language for game engine development; 2) In financial transaction systems, C's performance advantages ensure extremely low latency and high throughput; 3) In embedded systems, C's low-level memory management and efficient execution capabilities make it very popular in resource-constrained environments.

C   XML Frameworks: Choosing the Right One for YouC XML Frameworks: Choosing the Right One for YouApr 30, 2025 am 12:01 AM

The choice of C XML framework should be based on project requirements. 1) TinyXML is suitable for resource-constrained environments, 2) pugixml is suitable for high-performance requirements, 3) Xerces-C supports complex XMLSchema verification, and performance, ease of use and licenses must be considered when choosing.

C# vs. C  : Choosing the Right Language for Your ProjectC# vs. C : Choosing the Right Language for Your ProjectApr 29, 2025 am 12:51 AM

C# is suitable for projects that require development efficiency and type safety, while C is suitable for projects that require high performance and hardware control. 1) C# provides garbage collection and LINQ, suitable for enterprise applications and Windows development. 2)C is known for its high performance and underlying control, and is widely used in gaming and system programming.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software