任何使用函數的程式語言都具有更簡單、更模組化且在偵錯時更容易更改的程式碼。函數是模組化程式碼中非常有益的組成部分。函數可以接受參數並對其執行某些操作。與其他原始資料類型一樣,我們也可以將物件類型或陣列作為參數傳遞。在本文中,我們將看到如何在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 normals.
Syntax<return type> function_name ( string argument1, string argument2, … ) { // function body }
演算法
#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; }
Is "racecar" a palindrome? True Is "abcdef" a palindrome? False Is "madam" a palindrome? True Is "sir" a palindrome? False
(使用字元指標)
<return type> function_name ( char* <string variable>, … ) { // function body }Syntax
(使用字元陣列)
<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 腳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 ing in#to
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; }
Is "racecar" a palindrome? True Is "abcdef" a palindrome? False Is "madam" a palindrome? True Is "sir" a palindrome? False
Conclusion
以上是C++程式將字串傳遞給函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!