バックル8.ストリングの回転(ストリングの使用)

バックル8.回転ストリング

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

文字列(文字配列の形式で指定)とオフセットを指定原地すると、オフセットに従って(左から右に)文字列を回転させます。

 

 

アイデア:オフセットはサイクル数に等しく、サイクルごとに1つのオフセットで交換プロセスが完了します。

#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