c - 通过仅检查 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 中做到这一点?
解决方案
只需像其他答案一样比较字符。
但是,当然,您可以根据需要使用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
推荐阅读
- java - 以编程方式使用 JaCoCo API
- vb.net - 形式光标不变
- python - 绘制阈值(precision_recall 曲线)matplotlib/sklearn.metrics
- c++ - 给定一个仅由 4 个不同字母组成的字符串,它有多少个排列而没有两个连续的字母?
- c++ - C++中三角矩阵的嵌套循环
- python - Pandas Python 根据以下条件添加行
- node.js - 为什么第二个 console.log 先运行?
- java - 这是在 Java 中使用 private 的正确方法吗?
- python - 得到这个称为 TypeError 的错误:count() 至少需要 1 个参数(给定 0)
- ios - 当应用被用户杀死时如何重新启动位置更新?