データ構造 〜 第1章 配列と文字列 問題1-2

世界で闘うプログラミング力を鍛える150問 ~トップIT企業のプログラマになるための本~

世界で闘うプログラミング力を鍛える150問 ~トップIT企業のプログラマになるための本~

問題1-2。

CかC++で、void reverse(char* str)という'\0'終端の文字列を逆に並び替える関数を実装せよ。


文字列の前端と後端を順番に入れ替える。
長さnの文字列の場合、n/2の計算量。

void reverseChar(char* str){
	char* lastStrPointer;
	char tmpStr;

	lastStrPointer = str + strlen(str) - 1;

	while(str < lastStrPointer){
		//save the first string into tmpStr temporary
		tmpStr = *str;
		//change the two string
		*str++ = *lastStrPointer;
		*lastStrPointer-- = tmpStr;
	}

	return;
}

確認用のコードを含めたものは下記。

/*
 * prob12.c
 *
 *  Created on: 2014/01/07
 *      Author: graySpace999
 */
#include <stdio.h>
#include <stdlib.h>

void reverseChar(char* str);

int main(int argc, char **argv) {
	char word[256] = "abc";

	printf("%s%s\n","入れ替える前の文字は",word);
	reverseChar(word);
	printf("%s%s\n","入れ替えた後の文字は",word);
}

void reverseChar(char* str){
	char* lastStrPointer;
	char tmpStr;

	lastStrPointer = str + strlen(str) - 1;

	while(str < lastStrPointer){
		//save the first string into tmpStr temporary
		tmpStr = *str;
		//change the two string
		*str++ = *lastStrPointer;
		*lastStrPointer-- = tmpStr;
	}

	return;
}