スポンサーリンク

終端文字列が出現するまで、インデックスをループ処理

1つ目は、下記のように、終端文字列が出現するまで、配列のインデックスをwhile文でループ処理して参照する方法です。
ポインタを使うとみにくくなると感じるので、好きな方法です。

	i = 0;
	while(str[i] != '\0'){
		printf("%c ", str[i]);
		i++;
	}

スポンサーリンク

ポインタをインクリメントしながら、ポインタの指す先を参照

次は、ポインタをインクリメントしながら、ポインタの指す先を1文字ずつ参照していきます。
こちらも同様に、終端文字列が出現するまでwhile文でループ処理します。

	while(*tmpStr != '\0'){
		printf("%c ", *tmpStr);
		tmpStr++;
	}

strlen()で文字列の長さを取得し、文字列の長さ分ループ処理

strlen()で文字列の長さを取得し、for文で文字列の長さ分ループ処理する方法もあります。
こちらの方法もわかりやすくで好きな方法です。

	while(*tmpStr != '\0'){
		printf("%c ", *tmpStr);
		tmpStr++;
	}

スポンサーリンク

サンプルコード

下記がサンプルコードになります。

 $ cat sample.c 
#include <stdio.h>
#include <string.h>


int main(){
	int i;
	char* str = "string";
	char* tmpStr;
	
	i = 0;
	while(str[i] != '\0'){
		printf("%c ", str[i]);
		i++;
	}
	printf("\n");

	tmpStr = str;
	while(*tmpStr != '\0'){
		printf("%c ", *tmpStr);
		tmpStr++;
	}
	printf("\n");
	
	for(i = 0; i < strlen(str); i++){
		printf("%c ", str[i]);
	}
	printf("\n");
	
	return 0;
}

下記が実行結果になります。
 $ gcc -o sample sample.c
 $ ./sample 
s t r i n g 
s t r i n g 
s t r i n g 

スポンサーリンク