C - 字符串操作
在本教程中,我们将在C编程语言中了解字符串操作。
我们已经涵盖了如何在上一个教程中创建和初始化字符串。
所以,我们知道字符串是一系列中包含双引号的字符序列。
打印字符串的每个字符
我们在字符数组中保存一个字符串,我们知道数组元素是索引的。
因此,我们可以使用其索引号访问它们。
在以下示例中,我们有一个变量 str它包含一个字符串"hello",我们将在字符串中打印每个字符。
字符串以空结尾 \0C.中的特征
这里的诀窍是继续打印字符,只要我们没有击中标记C中的字符串末尾的空字符即可
所以,让我们写一个C程序。
#include <stdio.h>
int main(void)
{
//variable
char str[] = "Hello";
int i;
//output
i = 0;
while(str[i] != 'H
e
l
l
o
End of code
') {
printf("%c\n", str[i]);
i++;
}
printf("End of code\n");
return 0;
}
输出
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char str[] = "Hello";
printf("%ld", strlen(str)); //this will give us 5
return 0;
}
在字符串中查找总字符数
要找到我们使用的字符串中的字符总数 strlen()来自的函数 string.h标题文件。
下面给出了查找字符串长度的语法。 int len = strlen(str);其中: str是包含字符串的变量的名称。
以下代码将打印5,因为字符串"Hello"中有五个字符。
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char str1[100], str2[100];
//input
printf("Enter string 1: ");
gets(str1);
printf("Enter string 2: ");
gets(str2);
if (strcmp(str1, str2) == 0) {
printf("Both are same.\n");
}
else {
printf("Both are different.\n");
}
printf("End of code\n");
return 0;
}
比较两个字符串
比较C中的两个字符串我们使用 strcmp()从中的方法 string.h标题文件。
这 strcmp()函数将两个字符串进行比较,并将返回整数值。
如果返回的值为否,则String1 <string2 i.e.,String1在String2上面是lexly。
如果返回值为0,则String1和String2是相同的。
如果返回的值是正为正的,则String1> String2即,String1在String2下面是词汇表。
我们不能使用(str1 == str2)或者("hello"=="hi")来比较字符串。
在以下示例中,我们将使用两个字符串作为用户输入,并检查它们是否相等。
Enter string 1: Apple Enter string 2: Apple Both are same. End of code
相同的字符串
Enter string 1: Apple Enter string 2: Mango Both are different. End of code
不同的字符串
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char
str1[] = "Hello",
str2[] = "World",
str3[100] = "";
//concat
strcat(str3, str1); //concat "Hello" to str3 so, str3 = "Hello"
strcat(str3, " "); //concat " " to str3 so, str3 = "Hello "
strcat(str3, str2); //concat "World" to str3 so, str3 = "Hello World"
printf("Concatenated string: %s\n", str3);
printf("End of code\n");
return 0;
}
连接两个字符串
我们使用 concat()从中的函数 string.h标题文件要连接两个字符串。
在以下示例中,我们将连接"Hello"和"World"。
Concatenated string: Hello World End of code
输出
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char str[100], tmp;
int i, len, mid;
//input
printf("Enter a string: ");
gets(str);
//find number of characters
len = strlen(str);
mid = len/2;
//reverse
for (i = 0; i < mid; i++) {
tmp = str[len - 1 - i];
str[len - 1 - i] = str[i];
str[i] = tmp;
}
//output
printf("Reversed string: %s\n", str);
printf("End of code\n");
return 0;
}
反向字符串
要反转字符串,我们要做的就是将最后一个字符与第一个字符交换,第二个字符与第二个字符等,直到我们到达字符串的中间。
所以,如果我们有一个字符串"你好",那么它的反向是"olleh"。
在以下示例中,我们将拍摄少于100个字符的字符串,并将反转它。
Enter a string: Hello World Reversed string: dlroW olleH End of code
输出
##代码##
