うまく機能するグーグル中に以下のコードに出くわしました。(Chaitanya Bhatt @ Performancecompetence.com のクレジット)
以下の関数は、渡された区切り文字の最後の出現を検索し、入力文字列の残りの部分を返された出力文字列に保存します。
void strLastOccr(char inputStr[100], char* outputStr, char *delim)
{
char *temp, *temp2;
int i = 0;
temp = "";
while (temp!=NULL)
{
if(i==0)
{
temp2 = temp;
temp = (char *)strtok(inputStr,delim);
i++;
}
if(i>0)
{
temp2 = temp;
temp = (char *)strtok(NULL,delim);
}
lr_save_string(temp2,outputStr);
}
}
基本的に、渡す 2 つの新しいオプションを追加しようとしています。
出現番号:最後の出現にデフォルト設定する代わりに、特定の出現で停止して残りの文字列を保存できるようにします。
保存する文字列の一部: (左、右)現時点では、区切り文字が見つかると文字列の右側が保存されます。追加のオプションは、ユーザーが区切り文字の左側または右側を指定できるようにすることを目的としています。
void strOccr(char inputStr[100], char* outputStr, char *delim, int *occrNo, char *stringSide)
質問は、上記の関数に必要な変更は何ですか? また、実際にできるのでしょうか?
アップデート
私がそれを続けた後、私は解決策を練ることができました.
あと6時間は自分の質問に答えられないので、より良い機能を提供できる人にポイントが与えられます. 具体的には、「// 文字列の末尾にある delim を削除します」というコメントの下のコードが好きではありません。
void lr_custom_string_delim_save (char inputStr[500], char* outputStr, char *delim, int occrNo, int stringSide)
{
char *temp, *temp2;
char temp3[500] = {0};
int i = 0;
int i2;
int iOccrNo = 1;
temp = "";
while (temp!=NULL) {
if(i==0) {
temp2 = temp;
temp = (char *)strtok(inputStr,delim);
i++;
}
if(i>0) {
temp2 = temp;
temp = (char *)strtok(NULL,delim);
if (stringSide==0) {
if (iOccrNo > occrNo) {
strcat(temp3, temp2);
// Ensure an extra delim is not added at the end of the string.
if (temp!=NULL) {
// Adds the delim back into the string that is removed by strtok.
strcat(temp3, delim);
}
}
}
if (stringSide==1) {
if (iOccrNo <= occrNo) {
strcat(temp3, temp2);
strcat(temp3, delim);
}
}
// Increase the occurrence counter.
iOccrNo++;
}
}
// Removes the delim at the end of the string.
if (stringSide==1) {
for( i2 = strlen (temp3) - 1; i2 >= 0
&& strchr ( delim, temp3[i2] ) != NULL; i2-- )
// replace the string terminator:
temp3[i2] = '\0';
}
// Saves the new string to new param.
lr_save_string(temp3,outputStr);
}