search
HomeBackend DevelopmentC++C++ program to pass string to function
C++ program to pass string to functionAug 26, 2023 pm 12:17 PM
functionc programString passing

C++ program to pass string to function

Any programming language that uses functions has code that is simpler, more modular, and easier to change while debugging. Functions are a very beneficial part of modular code. Functions can accept parameters and perform certain operations on them. Like other primitive data types, we can also pass object types or arrays as parameters. In this article, we will see how to pass string type data as function parameter in C.

Pass parameters similar to C strings to functions

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

<return type> 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.

algorithm

  • 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
  • Define a function isPalindrome() which will accept the parameter s
  • revS := call reverse() by passing s to reverse the string s
  • If s and revS are the same, then
    • return True
  • otherwise
    • return False
  • end if
  • isPalindrome() function ends
The Chinese translation of

Example

is:

Example

#include <iostream>
#include <sstream>

using namespace std;
string reverse( string s ) {
   char temp;
   int n = s.length();
   for( int i = 0; i < n / 2; i++ ) {
      temp = s[i];
      s[i] = s[ n - i - 1 ];
      s[ n - i - 1 ] = temp;
   }
   return s;
}

string isPalindrome( string s ) {
   string revS = reverse( s );
   if( s == revS ) {
      return "True";
   }
   else {
      return "False";
   }
}

int main()
{
   cout << "Is "racecar" a palindrome? " << isPalindrome( "racecar" ) << endl;
   cout << "Is "abcdef" a palindrome? " << isPalindrome( "abcdef" ) << endl;
   cout << "Is "madam" a palindrome? " << isPalindrome( "madam" ) << endl;
   cout << "Is "sir" a palindrome? " << isPalindrome( "sir" ) << endl;
}

Output

Is "racecar" a palindrome? True
Is "abcdef" a palindrome? False
Is "madam" a palindrome? True
Is "sir" a palindrome? False

Passing C-like character array to a function

Since C supports almost all that is supported by C, we can also define strings using a character array like C. To pass C-like strings to a function, it must pass a character array or a character pointer to the base address of the string. The syntaxes are like below −

Syntax

(Use character pointer)

<return type> function_name ( char* <string variable>, … ) {
   // function body
}

Syntax

(Use character array)

<return type> function_name ( char <string variable>[], … ) {
   // function body
}

Let us see the same example of palindrome checking with character array passing. Here the reverse() function will modify the array, so we must pass this string as a character array, not the character pointer. And the isPalindrome() will just check whether the string is the same as the reversed string, so it can take character pointer or character array, and the effect will be the same. The algorithm is similar so we are directly entering into the code.

The Chinese translation of

Example

is:

Example

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

void reverse( char s[] ) {
   char temp;
   int n = strlen( s );
   for( int i = 0; i < n / 2; i++ ) {
      temp = s[i];
      s[i] = s[ n - i - 1 ];
      s[ n - i - 1 ] = temp;
   }
}

string isPalindrome( char* s ) {
   char* sRev = (char*) malloc( strlen(s) );
   strcpy( sRev, s );
   reverse( sRev );
   if( strcmp( sRev, s ) == 0 ) {
      return "True";
   }
   else {
      return "False";
   }
}

int main()
{
   string s = "racecar";
   cout << "Is "racecar" a palindrome? " << isPalindrome( const_cast<char*> (s.c_str()) ) << endl; 
   s = "abcdef";

   cout << "Is "abcdef" a palindrome? " << isPalindrome( const_cast<char*> (s.c_str()) ) << endl; 
   s = "madam";

   cout << "Is "madam" a palindrome? " << isPalindrome( const_cast<char*> (s.c_str()) ) << endl; 
   s = "sir";

   cout << "Is "sir" a palindrome? " << isPalindrome( const_cast<char*> (s.c_str()) ) << endl;
}

Output

Is "racecar" a palindrome? True
Is "abcdef" a palindrome? False
Is "madam" a palindrome? True
Is "sir" a palindrome? False

In this example, we see that there are several steps to adjusting C-style strings in C. For C-style strings, use the cstring library for length, string comparison, and other operations. To convert from C string to C string, you need to use the c_str() function, but this function returns const char*. However, our function only accepts data of type char*. For this case, we need to use const_cast to convert the value to char* type.

Conclusion

The function can accept primitive data types as well as arrays, object types, etc. When we use strings, in C they are object types and in C they are character array types. But since C also supports C syntax, it is also valid in C. Passing a string object is simple, but passing a character array requires special attention and following some strict steps. C-style strings can be passed in array format or as character pointers. When we know that the function will modify the string itself, we must pass the string as a character array, otherwise, modifying the string from a pointer is not allowed. When strings are only used, we can pass them using pointers or character arrays, and the effect is the same. But in this case passing via character array is good as it will prevent unintentional updates to the string.

The above is the detailed content of C++ program to pass string to function. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
提高 Python 代码可读性的五个基本技巧提高 Python 代码可读性的五个基本技巧Apr 12, 2023 pm 08:58 PM

Python 中有许多方法可以帮助我们理解代码的内部工作原理,良好的编程习惯,可以使我们的工作事半功倍!例如,我们最终可能会得到看起来很像下图中的代码。虽然不是最糟糕的,但是,我们需要扩展一些事情,例如:load_las_file 函数中的 f 和 d 代表什么?为什么我们要在 clay 函数中检查结果?这些函数需要什么类型?Floats? DataFrames?在本文中,我们将着重讨论如何通过文档、提示输入和正确的变量名称来提高应用程序/脚本的可读性的五个基本技巧。1. Comments我们可

CRPS:贝叶斯机器学习模型的评分函数CRPS:贝叶斯机器学习模型的评分函数Apr 12, 2023 am 11:07 AM

连续分级概率评分(Continuous Ranked Probability Score, CRPS)或“连续概率排位分数”是一个函数或统计量,可以将分布预测与真实值进行比较。机器学习工作流程的一个重要部分是模型评估。这个过程本身可以被认为是常识:将数据分成训练集和测试集,在训练集上训练模型,并使用评分函数评估其在测试集上的性能。评分函数(或度量)是将真实值及其预测映射到一个单一且可比较的值 [1]。例如,对于连续预测可以使用 RMSE、MAE、MAPE 或 R 平方等评分函数。如果预测不是逐点

详解JavaScript函数如何实现可变参数?(总结分享)详解JavaScript函数如何实现可变参数?(总结分享)Aug 04, 2022 pm 02:35 PM

js是弱类型语言,不能像C#那样使用param关键字来声明形参是一个可变参数。那么js中,如何实现这种可变参数呢?下面本篇文章就来聊聊JavaScript函数可变参数的实现方法,希望对大家有所帮助!

盘点Python内置函数sorted()高级用法实战盘点Python内置函数sorted()高级用法实战May 13, 2023 am 10:34 AM

一、前言前几天在Python钻石交流群有个叫【emerson】的粉丝问了一个Python排序的问题,这里拿出来给大家分享下,一起学习下。其实这里【瑜亮老师】、【布达佩斯的永恒】等人讲了很多,只不过对于基础不太好的小伙伴们来说,还是有点难的。不过在实际应用中内置函数sorted()用的还是蛮多的,这里也单独拿出来讲一下,希望下次再有小伙伴遇到的时候,可以不慌。二、基础用法内置函数sorted()可以用来做排序,基础的用法很简单,看个例子,如下所示。lst=[3,28,18,29,2,5,88

学Python,还不知道main函数吗学Python,还不知道main函数吗Apr 12, 2023 pm 02:58 PM

Python 中的 main 函数充当程序的执行点,在 Python 编程中定义 main 函数是启动程序执行的必要条件,不过它仅在程序直接运行时才执行,而在作为模块导入时不会执行。要了解有关 Python main 函数的更多信息,我们将从如下几点逐步学习:什么是 Python 函数Python 中 main 函数的功能是什么一个基本的 Python main() 是怎样的Python 执行模式Let’s get started什么是 Python 函数相信很多小伙伴对函数都不陌生了,函数是可

Python面向对象里常见的内置成员介绍Python面向对象里常见的内置成员介绍Apr 12, 2023 am 09:10 AM

好嘞,今天我们继续剖析下Python里的类。[[441842]]先前我们定义类的时候,使用到了构造函数,在Python里的构造函数书写比较特殊,他是一个特殊的函数__init__,其实在类里,除了构造函数还有很多其他格式为__XXX__的函数,另外也有一些__xx__的属性。下面我们一一说下:构造函数Python里所有类的构造函数都是__init__,其中根据我们的需求,构造函数又分为有参构造函数和无惨构造函数。如果当前没有定义构造函数,那么系统会自动生成一个无参空的构造函数。例如:在有继承关系

go语言的形参占用内存吗go语言的形参占用内存吗Dec 28, 2022 pm 05:19 PM

形参变量在未出现函数调用时并不占用内存,只在调用时才占用,调用结束后将释放内存。形参全称“形式参数”,是函数定义时使用的参数;但函数定义时参数是没有任实际何数据的,因而在函数被调用前没有为形参分配内存,其作用是说明自变量的类型和形态以及在过程中的作用。

Golang函数的类型断言用法介绍Golang函数的类型断言用法介绍May 16, 2023 am 08:02 AM

Golang的函数类型断言是一个非常重要的特性,它可以让我们在函数中精细地控制变量的类型,从而更加方便地进行数据处理和转换。本文将介绍Golang函数的类型断言用法,希望能够对大家的学习有所帮助。一、什么是Golang函数的类型断言?Golang函数的类型断言可以理解为函数参数中所声明变量的类型具有多态性,这使得一个函数在不同的参数传递下可以灵活

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft