search
HomeBackend DevelopmentC#.Net TutorialAn article to talk about string operations in C language (case conversion, comparison, sorting, etc.)

字符串是 C语言 程序中经常处理的对象之一,下面本篇文章就来带大家聊聊C语言中的字符串处理,了解一些字符串操作函数,希望对大家有所帮助!

An article to talk about string operations in C language (case conversion, comparison, sorting, etc.)

字符串在C语言里使用非常多,因为很多数据处理都是文本,也就是字符串,特别是设备交互、web网页交互返回的几乎都是文本数据。

字符串本身属于字符数组、只不过和字符数组区别是,字符串结尾有’\0’。 字符串因为规定结尾有'\0',在计算长度、拷贝、查找、拼接操作都很方便。

1. 字符串的定义

char buff[]="我是一个字符串";
char a[]="1234567890";
char b[]="abc";
char c[]={'a','b','c','\0'};

在普通的字符数组结尾加一个 \0 就变成了字符串。

2. 处理字符串里字母大小写

将字符串里所有大写字母全部换成小写字母。或者小写字母全部换成大写字母。可以通过形参进行区分。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void func(char *str,int flag);
int main()
{
    char buff[100];
    printf("从键盘上输入字符串:");
    scanf("%s",buff);
    printf("源字符串:%s\n",buff);
    func(buff,0);
    printf("大写转换小写:%s\n",buff);
    func(buff,1);
    printf("小写转大写:%s\n",buff);
    return 0;
}

//函数功能: 大写小写转换
//flag=0表示大写转换小写  =1表示小写转大写
void func(char *str,int flag)
{
    int data;
    while(*str!=&#39;\0&#39;)
    {
        if(flag)
        {
            if(*str>=&#39;a&#39;&& *str<=&#39;z&#39;) //小写
            {
                *str=*str-32;
            }
        }
        else
        {
            if(*str>=&#39;A&#39;&& *str<=&#39;Z&#39;) //小写
            {
                *str=*str+32;
            }
        }
        str++;
    }
}

3. 从键盘上录入2个字符串,判断是否相等

#include <stdio.h>
int main()
{
    char str1[100];
    char str2[100];
    int i=0;
    /*1. 录入数据*/
    printf("输入字符串1:");
    scanf("%s",str1);
    printf("输入字符串2:");
    scanf("%s",str2);
    /*2. 比较字符串*/
    while(str1[i]!=&#39;\0&#39;||str2[i]!=&#39;\0&#39;)
    {
        if(str1[i]!=str2[i])break;
        i++;
    }
    if(str1[i]==&#39;\0&#39;&&str2[i]==&#39;\0&#39;)
    {
        printf("字符串相等.\n");
    }
    else
    {
        printf("字符串不相等.\n");
    }
    return 0;
}

4. 从键盘上录入一个字符串,按照小到大的顺序排序

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

int main()
{
    char str1[100];
    int len=0;
    int i,j;
    int tmp;
    printf("输入要排序的字符串:");
    scanf("%s",str1);
    len=strlen(str1);
    //开始排序
    for(i=0;i<len-1;i++)
    {
        for(j=0;j<len-1-i;j++)
        {
            if(str1[j]>str1[j+1])
            {
                tmp=str1[j];
                str1[j]=str1[j+1];
                str1[j+1]=tmp;
            }
        }
    }
    printf("排序之后的字符串:%s\n",str1);
    return 0;
}

5. 从键盘上输入一个字符串,转为整数输出

#include <stdio.h>
#include <string.h>
int main()
{
    //"123"
    char str[100];
    int data=0;
    int i=0;
    printf("从键盘上输入字符串:");
    scanf("%s",str);
    while(str[i]!=&#39;\0&#39;)
    {
        data*=10;//data=0 data=10 data=120
        data+=str[i]-&#39;0&#39;;//data=1 data=12 data=123
        i++;
    }
    printf("data=%d\n",data);
    return 0;
}

6. 字符串删除

从键盘上录入一个字符串,删除字符串里指定的单词,输出结果。

比如:原字符串 ”akjbcds123dfjvbf123fdvbfd123”

删除单词:“123”

输出的结果:”akjbcdsdfjvbffdvbfd”

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

int main()
{
    char str1[100];
    char str2[100];
    int i=0,j=0;
    int str2_len=0;
    /*1. 录入数据*/
    printf("输入源字符串:");
    scanf("%s",str1);
    printf("输入要删除的字符串:");
    scanf("%s",str2);
    /*2. 计算要删除字符串的长度*/
    str2_len=strlen(str2);
                
    /*3. 查找字符串*/
    for(i=0;str1[i]!=&#39;\0&#39;;i++)
    {
        //比较字符串
        for(j=0;str2[j]!=&#39;\0&#39;;j++)
        {
            if(str1[i+j]!=str2[j])break;
        }
        if(str2[j]==&#39;\0&#39;)
        {
            //4. 删除字符串---后面向前面覆盖
            for(j=i;str1[j]!=&#39;\0&#39;;j++)
            {
                str1[j]=str1[j+str2_len];
            }
            str1[j]=&#39;\0&#39;;
            i--;
        }
    }
    //5. 输出结果
    printf("str1=%s\n",str1);
    return 0;
}

7. 字符串插入

从键盘上录入一个字符串,从指定位置插入一个字符串,再输出结果。

比如:原字符串“1234567890”

(1). 从指定位置插入新的单词。 比如 从第2个下标插入一个“ABC”字符串。

结果: “123ABC4567890”

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

int main()
{
    char str1[100];
    char str2[100];
    int addr=0;
    int str1_len;
    int str2_len;
    int i;
    /*1. 录入数据*/
    printf("录入源字符串:");
    scanf("%s",str1);
    printf("录入要插入的字符串:");
    scanf("%s",str2);
    printf("输入要插入的下标位置:");
    scanf("%d",&addr);
    str1_len=strlen(str1); //3
    str2_len=strlen(str2); //2
    
    /*2. 完成插入*/
    //完成数据移动
    for(i=str1_len-1;i>=addr;i--)
    {
        str1[i+str2_len]=str1[i];
    }
    //数据替换
    for(i=0;i<str2_len;i++)
    {
        str1[i+addr]=str2[i];
    }
    str1[str1_len+str2_len]=&#39;\0&#39;;
    /*3. 输出数据*/
    printf("str1=%s\n",str1);
    return 0;
}

8. 字符串替换

从键盘上录入一个字符串,将指定单词替换成想要的单词。

比如:原字符串“123jfvfdj123dkfvbfdvdf”

想要将“123”替换成“888”或者“8888”或者“88”

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

int main()
{
    char str1[100];
    char str2[100];
    char str3[100];
    int str1_len=0;
    int str2_len=0;
    int str3_len=0;
    int i,j;
    int cnt=0;
    /*1.准备数据*/
    printf("输入源字符串:");
    scanf("%s",str1);
    printf("输入查找的字符串:");
    scanf("%s",str2);
    printf("输入替换的字符串:");
    scanf("%s",str3);
    /*2. 计算长度*/
    str1_len=strlen(str1);
    str2_len=strlen(str2);
    str3_len=strlen(str3);
    /*3. 字符串替换*/
    for(i=0;i<str1_len;i++)
    {
        //查找字符串
        for(j=0;j<str2_len;j++)
        {
            if(str1[i+j]!=str2[j])break;
        }
        //如果查找成功就进行替换
        if(j==str2_len)
        {
            //总长度变短了
            if(str2_len>str3_len)
            {
                cnt=str2_len-str3_len; //差值
                //完成数据向前移动--覆盖
                for(j=i+str2_len-cnt;j<str1_len;j++)
                {
                    str1[j]=str1[j+cnt];
                }
                str1[str1_len-cnt]=&#39;\0&#39;;
            }
            //总长度变长了
            else if(str2_len<str3_len)
            {
                cnt=str3_len-str2_len; //差值
                //完成数据向后移动
                for(j=str1_len;j>=i+str2_len;j--)
                {
                    str1[j+cnt]=str1[j];
                }
                str1[str1_len+cnt]=&#39;\0&#39;;
            }
            //替换
            for(j=0;j<str3_len;j++)
            {
                str1[i+j]=str3[j];
            }
            //重新计算长度
            str1_len=strlen(str1);
        }
    }
    /*4. 完成字符串打印*/
    printf("str1=%s\n",str1);
    return 0;
}

相关推荐:《C视频教程

The above is the detailed content of An article to talk about string operations in C language (case conversion, comparison, sorting, etc.). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.