Table of Contents
1. 字符串的定义
2. 处理字符串里字母大小写
3. 从键盘上录入2个字符串,判断是否相等
4. 从键盘上录入一个字符串,按照小到大的顺序排序
5. 从键盘上输入一个字符串,转为整数输出
6. 字符串删除
7. 字符串插入
8. 字符串替换
Home Backend Development C#.Net Tutorial An article to talk about string operations in C language (case conversion, comparison, sorting, etc.)

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

Mar 30, 2022 pm 12:09 PM
c language String operations

字符串是 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'};
Copy after login

在普通的字符数组结尾加一个 \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++;
    }
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

相关推荐:《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 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

CS-Week 3 CS-Week 3 Apr 04, 2025 am 06:06 AM

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i

How to output a countdown in C language How to output a countdown in C language Apr 04, 2025 am 08:54 AM

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

How to define the call declaration format of c language function How to define the call declaration format of c language function Apr 04, 2025 am 06:03 AM

C language functions include definitions, calls and declarations. Function definition specifies function name, parameters and return type, function body implements functions; function calls execute functions and provide parameters; function declarations inform the compiler of function type. Value pass is used for parameter pass, pay attention to the return type, maintain a consistent code style, and handle errors in functions. Mastering this knowledge can help write elegant, robust C code.

The concept of c language functions and their definition format The concept of c language functions and their definition format Apr 03, 2025 pm 11:33 PM

C language functions are reusable code blocks, receive parameters for processing, and return results. It is similar to the Swiss Army Knife, powerful and requires careful use. Functions include elements such as defining formats, parameters, return values, and function bodies. Advanced usage includes function pointers, recursive functions, and callback functions. Common errors are type mismatch and forgetting to declare prototypes. Debugging skills include printing variables and using a debugger. Performance optimization uses inline functions. Function design should follow the principle of single responsibility. Proficiency in C language functions can significantly improve programming efficiency and code quality.

See all articles