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