0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C言語 文字を重複なしで出力するプログラム

Last updated at Posted at 2020-12-10

渡された文字列から、文字を重複なしで出力する

  • 一度出力した文字は出力しない
  • 出てきた順に出力する
  • 引数が2つ以外は改行を出力
  • 使用可能な関数はwriteのみ

※コメントで指摘いただきましたので、コードを訂正しました。ありがとうございます。

コード

# include <unistd.h>
# include <limits.h>

void ft_union(const char *s)
{
	static _Bool use_char[UCHAR_MAX + 1];

	if (!s)
		return;
	while (*s)
	{
		if (use_char[(unsigned char)*s] != 1)
		{
			write(1, s, 1);
			use_char[(unsigned char)*s] = 1;
		}
		s++;
	}
}

int main(int ac, const char **av)
{
	if (ac == 3)
	{
		ft_union(av[1]);
		ft_union(av[2]);
	}
	write(1, "\n", 1);
	return 0;
}

感想

一度、文字をフラグとして扱うアルゴリズムを理解してしまうと、他の書き方は冗長に思えて、書く気が起きない。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?