0

我目前正在通过 Stephen G. Kochan 的“Programming in C 3rd edition”一书学习 C。

练习要求我创建一个函数,将字符串中的字符串替换为另一个字符串。所以函数调用

replaceString(text, "1", "one");

将字符串文本中的“1”(如果存在)替换为“one”。

要完成这个练习,您需要函数findString()insertString()removeString()

这是 findString() 函数

int findString (const char source[], const char s[])
{
    int i, j;
    bool foundit = false;

    for ( i = 0; source[i] != '\0' && !foundit; ++i )
    {
        foundit = true;

        for ( j = 0; s[j] != '\0' && foundit; ++j )
            if ( source[j + i] != s[j] || source[j + i] == '\0' )
                foundit = false;

        if (foundit)
            return i;
    }

    return -1;
}

如果s[]在字符串source[]内,则返回一个整数,该整数等于字符串内s[]的起点。如果它没有找到s[],它将返回 -1。

insertString() 函数如下

void insertString (char source[], char s[], int index)
{
    int  stringLength (char string[]);
    int j, lenS, lenSource;

    lenSource = stringLength (source);
    lenS      = stringLength (s);

    if ( index > lenSource )
        return;

    for ( j = lenSource; j >= index; --j )
        source[lenS + j] = source[j];

    for ( j = 0; j < lenS; ++j )
        source[j + index] = s[j];
}

该函数采用三个参数,即source[]s[]index[]s[]是我想放入source[]的字符串,index[]是它应该开始的位置(例如 insertString("The son", "per", 4) 将源字符串设为 "The person") .

该函数包括另一个名为stringLength()的函数,其用途与名称相同。这是字符串长度()

int stringLength (char string[])
{
    int count = 0;

    while ( string[count] != '\0' )
        ++count;

    return count;
}

removeString ()接受三个参数,即wordicount。该函数删除另一个字符串中的一些字符。这个功能我还没有做出来。

总结一下,我的问题是:

我如何制作函数replaceString(),它在字符串中查找一个单词,如果它在那里,然后用另一个替换它?

这确实困扰了我一段时间,我非常感谢您在这方面的帮助。

更新

这是我到目前为止所做的代码

// replaceString() program

#include <stdio.h>
#include <stdbool.h>

int findString (char source[], char s[])
{
    int i, j;
    bool foundit = false;

    for ( i = 0; source[i] != '\0' && !foundit; ++i )
    {
        foundit = true;

        for ( j = 0; s[j] != '\0' && foundit; ++j )
            if ( source[j + i] != s[j] || source[j + i] == '\0' )
                foundit = false;

        if (foundit)
            return i;
    }

    return -1;
}

int stringLength (char string[])
{
    int count = 0;

    while ( string[count] != '\0' )
        ++count;

    return count;
}


void replaceString(char source[], char str1[], char str2[])
{
    int findString(char source[], char s[]);
    int stringLength(char string[]);
    int start;

    if ( findString(source, str1) == -1 )
        return;
    else
    {
        start = findString(source, str1);

        int lenSource = stringLength(source);
        int lenStr2   = stringLength(str2);
        int counter   = lenStr2;
        for ( lenSource; lenSource > start + lenStr2; --lenSource )
        {
            source[lenSource + lenStr2] = source[lenSource];
        }

        int i = 0;

        while ( i != counter )
        {
            source[start + i] = str2[i];
            ++i;
        }
    }
}

int main (void)
{
    void replaceString(char source[], char str1[], char str2[]);

    char string[] = "This is not a string";
    char s1[] = "not";
    char s2[] = "absolutely";

    printf ("Before: \n %s \n\n", string);

    replaceString(string, s1, s2);

    printf ("After: \n %s \n\n", string);

    return 0;
}

此代码提供以下输出:

之前:这不是字符串

之后:这绝对是

如您所见,我没有包含 removeString 函数(),因为我无法使该函数正常工作。我的程序中的错误在哪里?

4

3 回答 3

0

说你的replaceString()参数是(char source[], char s1[], char replacement[])

您需要使用在源代码findString()中查找s1。如果找到它,给定的位置s1,使用removeString()删除该字符串,然后insertString()插入replacement到该位置。

于 2013-10-24T16:17:29.640 回答
0

对于初学者,您的字符串长度是固定的。所以如果“目标”比“源”长,那么它就行不通了。插入字符串需要传入一个指针,然后你可以在堆上分配一个足够长的字符串来包含length(source)-length(remove) +length(add),然后返回那个指针

于 2013-10-24T16:14:30.143 回答
0

我也是编程新手。几天前我遇到了同样的练习,今天刚刚解决了。这是我的代码。

/* Programme to replace a string by using find, remove and insert
functions ex9.8.c */

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define MAX 501

// Function prototypes
void read_Line (char buffer[]);
int string_Length (char string[]);
int find_String (char string1[], char string2[]);
void remove_String (char source[], int start, int number);
void insert_String (char source[], int start, char input[]);
void replace_String (char origString[], char targetString[], char substString[]);

bool foundFirstCharacter = false;

int main(void)
{
    printf("This is a programme to replace part of a string.\n");
    printf("It can only handle up to 500 characters in total!\n");

    char text[MAX];
    bool end_Of_Text = false;
    int textCount = 0;

    printf("\nType in your source text.\n");
    printf("When you are done, press 'RETURN or ENTER'.\n\n");

    while (! end_Of_Text)
    {
        read_Line(text);

        if (text[0] == '\0')
        {
            end_Of_Text = true;
        }
        else
        {
            textCount += string_Length(text);
        }
        break;
    }

    // Declare variables to store seek string parameters
    int seekCount = 0;
    char seekString[MAX];

    printf("\nType in the string you seek.\n");
    printf("When you are done, press 'RETURN or ENTER'.\n\n");

    while (! end_Of_Text)
    {
        read_Line(seekString);

        if (seekString[0] == '\0')
        {
            end_Of_Text = true;
        }
        else
        {
            seekCount += string_Length(seekString);
        }
        break;
    }

    // Declare variables to store replacement string parameters
    int replCount = 0;
    char replString[MAX];

    printf("\nType in the replacement string.\n");
    printf("When you are done, press 'RETURN or ENTER'.\n\n");

    while (! end_Of_Text)
    {
        read_Line(replString);

        if (replString[0] == '\0')
        {
            end_Of_Text = true;
        }
        else
        {
            replCount += string_Length(replString);
        }
        break;
    }

    // Call the function
    replace_String (text, seekString, replString);

    return 0;
}

// Function to get text input
void read_Line (char buffer[])
{
    char character;
    int i = 0;

    do
    {
        character = getchar();
        buffer[i] = character;
        ++i;
    }
    while (character != '\n');

    buffer[i - 1] = '\0';
}

// Function to determine the length of a string
int string_Length (char string[])
{
    int len = 0;

    while (string[len] != '\0')
    {
        ++len;
    }

    return len;
}

// Function to find index of sub-string
int find_String (char string1[], char string2[])
{
    int i, j, l;
    int start;
    int string_Length (char string[]);

    l = string_Length(string2);

    for (i = 0, j = 0; string1[i] != '\0' && string2[j] != '\0'; ++i)
    {
        if (string1[i] == string2[j])
        {
            foundFirstCharacter = true;
            ++j;
        }
        else
        {
            j = 0;
        }
    }

    if (j == l)
    {
        start = i - j + 1;
        return start;
    }
    else
    {
        return j - 1;
    }
}

// Function to remove characters in string
void remove_String (char source[], int start, int number)
{
    int string_Length (char string[]);
    int i, j, l;
    char ch = 127;

    l = string_Length(source);
    j = start + number;

    for (i = start; i < j; ++i)
    {
        if (i >= l)
        {
            break;
        }
        source[i] = ch;
    }
    //printf("\nOutput: %s\n", source);
}

// Function to insert characters in string
void insert_String (char source[], int start, char input[])
{
    int string_Length (char string[]);
    int i, j, k, l, m;
    int srcLen;
    int inpLen;
    int totalLen;
    int endInsert;

    srcLen = string_Length(source);
    inpLen = string_Length(input);

    // Declare buffer array to hold combined strings
    totalLen = srcLen + inpLen + 3;
    char buffer[totalLen];

    // Copy from source to buffer up to insert position
    for (i = 0; i < start; ++i)
        buffer[i] = source[i];

    // Copy from input to buffer from insert position to end of input
    for (j = start, k = 0; k < inpLen; ++j, ++k)
        buffer[j] = input[k];

    endInsert = start + inpLen;

    for (m = start, l = endInsert; m <= srcLen, l < totalLen; ++m, ++l)
        buffer[l] = source[m];
    buffer[l] = '\0';

    printf("\nOutput: %s\n", buffer);
}

// Function to replace string
void replace_String (char origString[], char targetString[], char substString[])
{
    // Function prototypes to call
    void read_Line (char buffer[]);
    int string_Length (char string[]);
    int find_String (char string1[], char string2[]);
    void remove_String (char source[], int start, int number);
    void insert_String (char source[], int start, char input[]);

    // Search for target string in source text first
    int index;
    index = find_String (origString, targetString);
    if (index == -1)
    {
        printf("\nTarget string not in text. Replacement not possible!\n");
        exit(999);
    }

    // Remove found target string
    int lengthTarget;
    lengthTarget = string_Length(targetString);

    remove_String(origString, index - 1, lengthTarget);

    // Insert replacement string
    insert_String(origString, index, substString);
}

于 2020-09-16T21:16:23.940 回答