首页 > 解决方案 > 通过仅检查 char 数组的可变单个元素来使用 strncmp

问题描述

我正在尝试编写一个代码,将char数组的字母与确定的字母(字母'l')一一进行比较。当输出字符串中出现这种情况时,有两个 'l'。例如,“lily”应该变成“llilly”。我看不到如何在 C 中实现这一点,因为这样的事情:

strncmp (word[indx],'l',1)  //where indx is an iterator of the char array 'word'

无效,因为第一个参数应该是“单词”,但是没有办法遍历“单词”。

当然,如果我们写:

strncmp (word,'l',indx)

indx问题是现在我们在等于或大于 2后一次检查多个字母,而我们真正想要的是一次检查一个字符。

到目前为止,这是我的代码:

#include <stdio.h>
#include <string.h>

const char* ModifyString (char word []);

int main(){
  char word[6]="Hello";
  printf("The result is %s \n", ModifyString(word));
  return 0;
}

const char* ModifyString (char word []) {
  size_t lengthString=strlen(word);
  char modifiedString[lengthString*2+1]; //to fit the nul terminator and all the 'l's in case the word only contained 'l's.
  int indxModWord=0;

  for (int indx=0; indx<lengthString;indx++) {
    //This line does not express what I want to do:
    if (strncmp(word,"l",indx)==0) {
      modifiedString[indxModWord]=word[indx];
      indxModWord++;
    }

    // if 'l' in word make it appear twice in the output string
    else {
      modifiedString[indxModWord]='l';
      indxModWord++;
      modifiedString[indxModWord]='l';
      indxModWord++;
    }
  }

  printf("%s", modifiedString);
}

有谁知道我应该如何在 C 中做到这一点?

标签: c

解决方案


只需像其他答案一样比较字符。

但是,当然,您可以根据需要使用strncmp来比较字符。

strncmp (&word[indx],(char []){'l'},1);

或者你可以编写函数:

int compareCharsUsingStrncmp(const char a, const char b)
{
    return strncmp((char[]){a}, (char[]){b}, 1);
}

或者

int compareCharsUsingStrncmp(const char a, const char b)
{
    return strncmp(&a, &b, 1);
}

智能编译器甚至不会调用strncmp:)

compareCharsUsingStrncmp:
        movzx   eax, dil
        movzx   esi, sil
        sub     eax, esi
        ret

推荐阅读