zoukankan      html  css  js  c++  java
  • C/C++字符串反转的N种方法

    0x00 自己写一个

    // 第一种
    std::string reverse(std::string str)
    {
    	std::string res("");
    	for (int i = str.size() - 1; i >= 0; i--)
    	{
    		res += str[i];
    	}
    	return res;
    }
    // 第二种
    int main(void)
    {
    	std::string str("abcde");
    	int i = 0, j = str.size() - 1;
    	while (i < j)
    	{
    		// 交换
    		str[i] = str[j] ^ str[i];
    		str[j] = str[j] ^ str[i];
    		str[i] = str[j] ^ str[i];
    		j--;
    		i++;
    	}
    	std::cout << str.c_str() << std::endl;
    	return 0;
    }
    

    0x01 使用strrev函数

    int main(void)
    {
    	char s[] = "abcde";
    	strrev(s);
    	std::cout << s << std::endl;
    	return 0;
    }
    // 结果:edcba
    

    0x02 使用algorithm中的reverse

    #include <algorithm>
    int main(void)
    {
    	std::string str("abcde");
    	reverse(str.begin(),str.end());
    	std::cout << str.c_str() << std::endl;
    	return 0;
    }
  • 相关阅读:
    51nod 1081 子段求和
    51nod 1085 背包问题
    51nod 1012 最小公倍数LCM
    51nod 1046 A^B Mod C
    51nod 1057 N的阶乘
    死锁 必然
    two-sum
    一些基本定义
    常用命令
    python_99_面向对象多态
  • 原文地址:https://www.cnblogs.com/bk76120/p/10556037.html
Copyright © 2011-2022 走看看