我目前正在通过 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 ()接受三个参数,即word、i和count。该函数删除另一个字符串中的一些字符。这个功能我还没有做出来。
总结一下,我的问题是:
我如何制作函数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 函数(),因为我无法使该函数正常工作。我的程序中的错误在哪里?