C++程序将字符串传递给函数

2023年 8月 29日 62.3k 0

C++程序将字符串传递给函数

任何使用函数的编程语言都具有更简单、更模块化且在调试时更容易更改的代码。函数是模块化代码中非常有益的组成部分。函数可以接受参数并对其执行某些操作。与其他原始数据类型一样,我们也可以将对象类型或数组作为参数传递。在本文中,我们将看到如何在C++中将字符串类型的数据作为函数参数传递。

传递类似C++字符串的参数给函数

C++ supports stronger string objects which is actually a class with different member functions associated with them. A string object passing as an argument is similar to the passing of normal primitive datatypes. The syntax is also quite similar.

Syntax

function_name ( string argument1, string argument2, … ) {
// function body
}

登录后复制

In the following example, we will see a program to check whether a given string is a palindrome or not. There will be two functions, one will reverse the string, and another will check whether the string is palindrome or not. Let us see the algorithm and corresponding C++ implementation.

算法

  • define a function reverse(), this will take a string s
  • n := floor of (length of s / 2)
  • for i ranging from 0 to n/2; do
    • temp := s[i]
    • s[i] := s[ n - i - 1 ]
    • s[ n - i - 1 ] := temp
  • end for
  • return s
  • end of reverse() function
  • 定义一个函数 isPalindrome(),它将接受参数 s
  • revS := call reverse() by passing s to reverse the string s
  • 如果 s 和 revS 相同,则
    • return True
  • otherwise
    • return False
  • end if
  • isPalindrome()函数结束

Example

的中文翻译为:

示例

#include
#include

using namespace std;
string reverse( string s ) {
char temp;
int n = s.length();
for( int i = 0; i

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论