倒置函数reverse的用法

xiaoxiao2021-02-28  69

本文转载自http://blog.sina.com.cn/s/blog_a3cc698201018czr.html请尊重版权

倒置字符串函数reverse:用于倒置字符串s中的各个字符的位置,如原来字符串中如果初始值为123456,则通过reverse函数可将其倒置为654321,程序如下: #include<stdio.h> #include<string.h> void reverse(char s[]) {    int c,j,i;  for(i=0,j=strlen(s)-1;i<j;i++,j--)//完成倒置功能,不包括字符串结束符'/0'  {   c=s[i];   s[i]=s[j];   s[j]=c;  } } main()//主函数,用于测试reverse函数的功能 {    char s[]="123456";  reverse(s);//调用倒置函数  printf("倒置后的字符串为:%s/n",s);//输出倒置后的字符串 }

运行结果如下;654321

 

功能颠倒字符串中字符次序。  语法Reverse ( string )

  参数string:要颠倒字符次序的字符串返回值String。函数执行成功时返回颠倒字符次序后的字符串,如果发生错误,那么返回空字符串("")。用法Reverse()函数将一个字符串中最后一个字符放置到另一个字符串的第一个字符位置、倒数第二个字符放置在另一个字符串的第二个字符位置,以此类推。

  EXAMPLE:

  // reverse algorithm example

  #include <iostream>

  #include <algorithm>

  #include <vector>

  using namespace std;

  int main () {

  vector<int> myvector;

  vector<int>::iterator it;

  // set some values:

  for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

  reverse(myvector.begin(),myvector.end()); // 9 8 7 6 5 4 3 2 1

  // print out content:

  cout << "myvector contains:";

  for (it=myvector.begin(); it!=myvector.end(); ++it)

  cout << " " << *it;

  cout << endl;

  return 0;

  }

  Output:

  myvector contains: 9 8 7 6 5 4 3 2 1

 

转载请注明原文地址: https://www.6miu.com/read-56700.html

最新回复(0)