I'm still a little new to C, and one hiccup I've been stuck on for the past bit is iterating through a char array received as a parameter. The char array was created as a String literal and passed as an argument. From my understanding this array being received as simply a pointer to the first element in the array; my goal is to loop through each element until reaching the end of the String literal that was passed.
我对C仍然是一个新手,并且我一直坚持过去的一个打嗝是迭代通过作为参数接收的char数组。 char数组创建为String文字并作为参数传递。根据我的理解,这个数组只是一个指向数组中第一个元素的指针;我的目标是循环遍历每个元素,直到到达传递的String文字的末尾。
Since I'm required to perform comparisons of each char to char literals inside the loop, I've assigned the value being pointed at in the array, to a char variable that is being used for the comparisons.
由于我需要在循环内对每个char进行char字符串的比较,因此我已将数组中指向的值分配给用于比较的char变量。
Where I'm having trouble is specifying at what point this loop should end.
我遇到麻烦的地方是指定这个循环应该在什么时候结束。
int main (int argc, char* argv[])
{
testString("the quick brown fox jumped over the lazy dog");
return EXIT_SUCCESS;
}
void testString(char line[])
{
int i = 0;
int j = 0;
char ch;
ch = line[i];
char charArray[128];
while (ch != '\0') // Not sure why this doesn't work
{
if ((ch == '\'' || ch == '-'))
{
charArray[j] = ch;
j++;
}
else if (isalpha(ch))
{
charArray[j] = ch;
j++;
}
else
{
// do nothing
}
i++;
ch = line[i];
}
}
Thanks in advance for any advice you can offer.
提前感谢您提供的任何建议。
1 个解决方案
#1
2
The exit condition for your loop is working fine.
你的循环的退出条件工作正常。
The only thing missing is that you need to null terminate charArray
after the while
loop and print it out:
唯一缺少的是你需要在while循环之后null终止charArray并将其打印出来:
while (ch != '\0')
{
...
}
charArray[j] = '\0';
printf("charArray=%s\n",charArray);
#1
2
The exit condition for your loop is working fine.
你的循环的退出条件工作正常。
The only thing missing is that you need to null terminate charArray
after the while
loop and print it out:
唯一缺少的是你需要在while循环之后null终止charArray并将其打印出来:
while (ch != '\0')
{
...
}
charArray[j] = '\0';
printf("charArray=%s\n",charArray);