文字列処理

[C言語] 文字列の一部を切り出す方法を解説

C言語で文字列の一部を切り出すには、標準ライブラリの関数を利用するか、自作の関数を作成する方法があります。

標準ライブラリには直接文字列を切り出す関数は存在しないため、strncpy関数を使って部分文字列をコピーするのが一般的です。

また、malloc関数を用いて新しいメモリ領域を確保し、そこに切り出した文字列を格納する方法もあります。

これにより、元の文字列を変更せずに部分文字列を取得することが可能です。

文字列の一部を切り出す方法

C言語で文字列の一部を切り出す方法はいくつかあります。

ここでは、strncpy関数、ポインタ、ループ、memcpy関数を使った方法を解説します。

strncpy関数の使い方

strncpy関数は、指定した長さ分だけ文字列をコピーするために使用されます。

以下に基本的な使い方を示します。

#include <stdio.h>
#include <string.h>
int main() {
    char source[] = "Hello, World!";
    char destination[6];
    // sourceから5文字をdestinationにコピー
    strncpy(destination, source, 5);
    destination[5] = '
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[6];
// sourceから5文字をdestinationにコピー
strncpy(destination, source, 5);
destination[5] = '\0'; // 終端文字を追加
printf("切り出した文字列: %s\n", destination);
return 0;
}
'; // 終端文字を追加 printf("切り出した文字列: %s\n", destination); return 0; }
切り出した文字列: Hello

この例では、strncpyを使って”Hello, World!”から最初の5文字を切り出しています。

strncpyは終端文字を自動で追加しないため、手動で追加する必要があります。

ポインタを使った切り出し

ポインタを使うことで、文字列の任意の位置から部分文字列を切り出すことができます。

#include <stdio.h>
int main() {
    char source[] = "Hello, World!";
    char *start = source + 7; // "World!"の開始位置
    char destination[6];
    // ポインタを使って切り出し
    strncpy(destination, start, 5);
    destination[5] = '
#include <stdio.h>
int main() {
char source[] = "Hello, World!";
char *start = source + 7; // "World!"の開始位置
char destination[6];
// ポインタを使って切り出し
strncpy(destination, start, 5);
destination[5] = '\0'; // 終端文字を追加
printf("切り出した文字列: %s\n", destination);
return 0;
}
'; // 終端文字を追加 printf("切り出した文字列: %s\n", destination); return 0; }
切り出した文字列: World

この例では、ポインタを使って”Hello, World!”の中から”World”を切り出しています。

ポインタを使うことで、文字列の任意の位置から簡単に切り出すことができます。

ループを使った手動切り出し

ループを使って手動で文字列を切り出す方法もあります。

これにより、より柔軟な操作が可能です。

#include <stdio.h>
int main() {
    char source[] = "Hello, World!";
    char destination[6];
    int start = 7; // "World!"の開始位置
    int length = 5;
    // ループを使って手動で切り出し
    for (int i = 0; i < length; i++) {
        destination[i] = source[start + i];
    }
    destination[length] = '
#include <stdio.h>
int main() {
char source[] = "Hello, World!";
char destination[6];
int start = 7; // "World!"の開始位置
int length = 5;
// ループを使って手動で切り出し
for (int i = 0; i < length; i++) {
destination[i] = source[start + i];
}
destination[length] = '\0'; // 終端文字を追加
printf("切り出した文字列: %s\n", destination);
return 0;
}
'; // 終端文字を追加 printf("切り出した文字列: %s\n", destination); return 0; }
切り出した文字列: World

この例では、ループを使って”Hello, World!”の中から”World”を切り出しています。

ループを使うことで、より細かい制御が可能です。

memcpy関数を利用した方法

memcpy関数を使うことで、バイナリデータとして文字列をコピーすることができます。

これも文字列の一部を切り出すのに有効です。

#include <stdio.h>
#include <string.h>
int main() {
    char source[] = "Hello, World!";
    char destination[6];
    // memcpyを使って切り出し
    memcpy(destination, source + 7, 5);
    destination[5] = '
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[6];
// memcpyを使って切り出し
memcpy(destination, source + 7, 5);
destination[5] = '\0'; // 終端文字を追加
printf("切り出した文字列: %s\n", destination);
return 0;
}
'; // 終端文字を追加 printf("切り出した文字列: %s\n", destination); return 0; }
切り出した文字列: World

この例では、memcpyを使って”Hello, World!”の中から”World”を切り出しています。

memcpyはバイナリデータをそのままコピーするため、終端文字を手動で追加する必要があります。

応用例

文字列の一部を切り出す技術は、さまざまな応用が可能です。

ここでは、部分文字列の検索と切り出し、文字列のトリミング、文字列の分割、文字列の置換について解説します。

部分文字列の検索と切り出し

部分文字列を検索して切り出すには、strstr関数を使うことができます。

strstrは、文字列の中から特定の部分文字列を検索し、その位置を返します。

#include <stdio.h>
#include <string.h>
int main() {
    char source[] = "Hello, World!";
    char *found = strstr(source, "World");
    if (found != NULL) {
        char destination[6];
        strncpy(destination, found, 5);
        destination[5] = '
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char *found = strstr(source, "World");
if (found != NULL) {
char destination[6];
strncpy(destination, found, 5);
destination[5] = '\0'; // 終端文字を追加
printf("見つかった部分文字列: %s\n", destination);
} else {
printf("部分文字列が見つかりませんでした。\n");
}
return 0;
}
'; // 終端文字を追加 printf("見つかった部分文字列: %s\n", destination); } else { printf("部分文字列が見つかりませんでした。\n"); } return 0; }
見つかった部分文字列: World

この例では、strstrを使って”Hello, World!”の中から”World”を検索し、見つかった部分を切り出しています。

文字列のトリミング

文字列のトリミングは、文字列の先頭や末尾から不要な空白を取り除く操作です。

以下は、手動でトリミングを行う例です。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
void trim(char *str) {
    char *end;
    // 先頭の空白をスキップ
    while (isspace((unsigned char)*str)) str++;
    if (*str == 0)  // すべて空白の場合
        return;
    // 末尾の空白をスキップ
    end = str + strlen(str) - 1;
    while (end > str && isspace((unsigned char)*end)) end--;
    // 新しい終端文字を追加
    *(end + 1) = '
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void trim(char *str) {
char *end;
// 先頭の空白をスキップ
while (isspace((unsigned char)*str)) str++;
if (*str == 0)  // すべて空白の場合
return;
// 末尾の空白をスキップ
end = str + strlen(str) - 1;
while (end > str && isspace((unsigned char)*end)) end--;
// 新しい終端文字を追加
*(end + 1) = '\0';
}
int main() {
char str[] = "   Hello, World!   ";
trim(str);
printf("トリミング後の文字列: '%s'\n", str);
return 0;
}
'; } int main() { char str[] = " Hello, World! "; trim(str); printf("トリミング後の文字列: '%s'\n", str); return 0; }
トリミング後の文字列: 'Hello, World!'

この例では、trim関数を使って文字列の先頭と末尾の空白を取り除いています。

文字列の分割

文字列を特定の区切り文字で分割するには、strtok関数を使います。

以下にその例を示します。

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "apple,banana,cherry";
    char *token;
    // カンマで分割
    token = strtok(str, ",");
    while (token != NULL) {
        printf("分割された文字列: %s\n", token);
        token = strtok(NULL, ",");
    }
    return 0;
}
分割された文字列: apple
分割された文字列: banana
分割された文字列: cherry

この例では、strtokを使ってカンマで文字列を分割し、それぞれの部分を出力しています。

文字列の置換

文字列の一部を別の文字列に置換するには、手動で行う必要があります。

以下は、簡単な置換の例です。

#include <stdio.h>
#include <string.h>
void replace(char *str, const char *oldWord, const char *newWord) {
    char buffer[256];
    char *pos;
    // 置換する単語を検索
    pos = strstr(str, oldWord);
    if (pos == NULL) return;
    // 置換後の文字列を作成
    strncpy(buffer, str, pos - str);
    buffer[pos - str] = '
#include <stdio.h>
#include <string.h>
void replace(char *str, const char *oldWord, const char *newWord) {
char buffer[256];
char *pos;
// 置換する単語を検索
pos = strstr(str, oldWord);
if (pos == NULL) return;
// 置換後の文字列を作成
strncpy(buffer, str, pos - str);
buffer[pos - str] = '\0';
sprintf(buffer + (pos - str), "%s%s", newWord, pos + strlen(oldWord));
// 元の文字列にコピー
strcpy(str, buffer);
}
int main() {
char str[256] = "Hello, World!";
replace(str, "World", "C Programming");
printf("置換後の文字列: %s\n", str);
return 0;
}
'; sprintf(buffer + (pos - str), "%s%s", newWord, pos + strlen(oldWord)); // 元の文字列にコピー strcpy(str, buffer); } int main() { char str[256] = "Hello, World!"; replace(str, "World", "C Programming"); printf("置換後の文字列: %s\n", str); return 0; }
置換後の文字列: Hello, C Programming!

この例では、replace関数を使って”Hello, World!”の”World”を”C Programming”に置換しています。

手動で置換を行うため、バッファサイズに注意が必要です。

まとめ

文字列の一部を切り出す方法は、C言語での文字列操作の基本的な技術です。

strncpyやポインタ、ループ、memcpyを使った切り出し方法を理解することで、文字列操作の幅が広がります。

この記事を参考に、実際のプログラムでこれらの技術を活用してみてください。

関連記事

Back to top button