力扣8. 旋转字符串(字符串用法)

力扣8. 旋转字符串

https://www.lintcode.com/problem/rotate-string/description

给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。

思路:偏移几位等于循环次数;完成交换过程,每循环一次偏移一个

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
	/**
	* @param str: An array of char
	* @param offset: An integer
	* @return: nothing
	*/
	void rotateString(string &str, int offset) {
		// write your code here
		if (offset > 0 && str.length() > 0)
		{
			int moffset = offset % str.length();//取余,倍数是循环多少次,余数才是偏移量
			char strbefore = str[0];
			for (int j = 1; j <= moffset; j++)//偏移几位等于循环次数
			{
				char strend = str[str.length() - 1];//末尾
				for (int i = 1; i < str.length(); i++)//完成交换过程,每循环一次偏移一个
				{
					char temp = str[i];
					str[i] = strbefore;
					strbefore = temp;
				}
				str[0] = strend;
			}
		}
	}
};

int main()
{
	Solution s;
	string str="abcdefg";
	s.rotateString(str, 25);
	cout<<str<<endl;
	char streabcdefgnd = str[str.length() - 1];
	return 0;
}

附字符串用法:

参考:http://c.biancheng.net/stl/string/

包含头文件:#include<cstring>    //注意这里不是string.h。

1.strlen 函数:strlen 函数将接收一个 C 字符串作为实参,并返回字符串的长度
例如:

  char str[] = "Hello";
  int length = strlen(str);

length=5.

2.strcat 函数:strcat 函数釆用两个字符串作为形参并连接它们,返回由第一个字符串和第二个字符串的所有字符组成的单个字符串

例如:const int SIZE = 13;char string1[SIZE] = "Hello ";char string2 [ ] = "World!";

           cout << string1 << endl;

           cout << string2 << endl;strcat(string1, string2);

           cout << string1 << endl;
输出结果是:
Hello
World!
Hello World!

3.strcpy 函数:strcpy 函数可以用来将一个字符串复制到另一个字符串中
例如:char string1 [ ] = "Hello ";

           cout << string1 << endl;

           strcpy(string1, "World!");

           cout << string1;

输出结果:

Hello
World!

4.strcmp 函数:strcmp函数以两个 C 字符串作为形参,并返回一个整数,表示两个字符串相互比较的结果

例如:if (strcmp(stringl, string2) == 0)

           cout << "The strings are equal";

           else

           cout << "The strings are not equal";

相等输出"The strings are equal";不等:"The strings are not equal";



发布了23 篇原创文章 · 获赞 0 · 访问量 137

猜你喜欢

转载自blog.csdn.net/qq_35683407/article/details/105397856