という関数を作りたいですremstr()
。この関数は、を使用せずにstring.h
、指定された文字列を別の文字列から削除します。例:
str1[30]= "go over stackover"
str2[20]= "ver"
strrem[20]= "go o stacko"
私を助けてください
C には、これを行うための便利なビルディング ブロックが多数用意されています。特に、次の 3 つの標準ライブラリ関数を使用してこの関数を作成できます: strstr
(削除する文字列を見つけるため)、strlen
残りの文字列の長さを計算するため、およびmemcpy
削除したくない部分を宛先 (関数をその場で動作させたい場合は、memmove
代わりに使用する必要があります)。memcpy
3 つの関数はすべて で宣言されてい<string.h>
ます。
関数を書くのに一苦労し、問題が発生した場合は具体的な質問をしてください。
擬似コードは、やりたいことを非常に簡単に実行できます。関数を使用できない場合は、string.h
関数を再作成するだけです。
char * remstr(char *str1, char * str2)
{
get length of str1
get length of str2
for(count from 0 to length of str2 - length of str1) {
if ( str1[count] != str2[count])
store str2[count] in to your new string
else
loop for the length of str1 to see if all character match
hold on to them in case they don't and you need to add them into you
new string
}
return your new string
}
詳細を理解する必要がありますremstr()
が、新しい文字列にメモリを割り当てますか?既存の文字列を取得して更新しますか?あなたの弦の番兵のキャラクターは何ですか?
これを機能させるには、を使用する必要がありますstrlen()
。使用できないため、次のようなものを作成する必要があります。
int mystrlen(char* str) {
while not at the sentinel character
increment count
return count
}
#include <stdio.h>
#include <stdlib.h>
void remstr(char *str1, char *str2, char *strrem)
{
char *p1, *p2;
if (!*str2) return;
do {
p2 = str2;
p1 = str1;
while (*p1 && *p2 && *p1==*p2) {
p1++;
p2++;
}
if (!(*p2)) str1 = p1-1;
else *strrem++ = *str1;
} while(*str1 && *(++str1));
*strrem = '\0';
}
int main() {
char str1[30]= "go over stackover";
char str2[20]= "ver";
char strrem[30];
remstr(str1, str2, strrem);
printf("%s\n",strrem);
}
この関数を使用すると、結果を同じ文字列バッファーに入れることもできますstr1
。
remstr(str1, str2, str1);
printf("%s\n",str1);