21xrx.com
2024-06-03 02:08:53 Monday
登录
文章检索 我的文章 写文章
C++字符串函数完全指南
2023-07-02 05:52:00 深夜i     --     --
C++ 字符串函数 完全指南

C++是一种强大的编程语言,里面有各种各样的函数可以使用。其中,字符串函数是非常重要的一类函数,在实际的编程工作中也经常被使用到。本文将为您提供一份C++字符串函数完全指南。

1. 字符串输出函数:cout

cout是C++中的标准输出函数,用于将字符串输出到屏幕。例如:


#include <iostream>

using namespace std;

int main()

  cout << "Hello World!" << endl;

  return 0;

以上代码将在屏幕上输出“Hello World!”,并添加一个换行符。

2. 字符串输入函数:cin

cin是C++中的标准输入函数,用于从键盘输入数据。可以使用cin从键盘中获取字符串。例如:


#include <iostream>

#include <string>

using namespace std;

int main()

  string str;

  cout << "请输入一个字符串:";

  cin >> str;

  cout << "您输入的字符串是:" << str << endl;

  return 0;

以上代码将提示用户输入一个字符串,接着使用cin获取用户输入的字符串,并将该字符串输出到屏幕上。

3. 字符串长度函数:strlen

strlen用于获取一个字符串的长度。例如:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str[] = "Hello World!";

  cout << "字符串长度为:" << strlen(str) << endl;

  return 0;

}

以上代码将输出“字符串长度为:12”,因为“Hello World!”是一个12个字符的字符串。

4. 字符串拼接函数:strcat

strcat可以将两个字符串拼接在一起。例如:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "Hello";

  char str2[] = "World!";

  strcat(str1, str2);

  cout << "拼接后的字符串为:" << str1 << endl;

  return 0;

}

以上代码将输出“拼接后的字符串为:HelloWorld!”,因为strcat将字符串“World!”拼接在“Hello”的后面。

5. 字符串复制函数:strcpy

strcpy可以将一个字符串复制到另一个字符串中。例如:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "Hello";

  char str2[10];

  strcpy(str2, str1);

  cout << "复制后的字符串为:" << str2 << endl;

  return 0;

}

以上代码将输出“复制后的字符串为:Hello”,因为strcpy将str1复制到了str2中。

6. 字符串比较函数:strcmp

strcmp可以比较两个字符串是否相等。例如:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "Hello";

  char str2[] = "hello";

  if (strcmp(str1, str2) == 0)

  {

    cout << "字符串相等" << endl;

  }

  else

  {

    cout << "字符串不相等" << endl;

  }

  return 0;

}

以上代码将输出“字符串不相等”,因为strcmp区分大小写。

7. 字符串查找函数:strstr

strstr可以在一个字符串中查找另一个字符串。例如:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "Hello World!";

  char str2[] = "World";

  if (strstr(str1, str2) != NULL)

  {

    cout << "包含子串" << endl;

  }

  else

  {

    cout << "不包含子串" << endl;

  }

  return 0;

}

以上代码将输出“包含子串”,因为字符串“Hello World!”包含了子串“World”。

本文介绍了一些C++中常用的字符串函数,对于需要使用字符串的程序员来说,这些函数是非常重要的。通过熟练使用这些函数,可以轻松地处理字符串操作。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复