指向字符串C [英] Pointers to string C
本文介绍了指向字符串C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试编写功能,如果中字每个字母出现在S返回1。
例如:

containsLetters1(this_is_a_long_string,气)返回1
containsLetters1(this_is_a_longstring,嘎斯)返回0
containsLetters1(你好,P)返回0
块引用>不明白为什么它不正确的:
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#定义MAX_STRING 100INT containsLetters1(字符* S,字符*字)
{
INT J,I,标志;
长LEN;
LEN = strlen的(字);对于(i = 0; I< = LEN;我++){
标志= 0;
为(J = 0; J< MAX_STRING; J ++){
如果(字== S){
标志= 1;
字++;
小号++;
打破;
}
小号++; }
如果(标志== 0){
打破;
}
}
返回标志;
}诠释主(){
字符字符串1 [MAX_STRING] 1,字符串[MAX_STRING]的printf(请输入2字符串containsLetters1 \\ n);scanf函数(%s%S,字符串1,字符串);的printf(从containsLetters1返回值是:%d个\\ N,containsLetters1(字符串1,字符串)); 返回0;
解决方案尝试这些:
为(i = 0; I< LEN,我++)...
(使用<而非< =,否则你会采取一个额外的字符);如果(字== S)
应如果(*字== * S)
(你比较存储在尖的位置,而不是指针)字符;- 指针小号的进步,但它应该得到回字
取值
,达到其目的,即在S的开始 - = LEN
在为(J = ...)
;取值++
字++
后是不需要的,你按相同的量超前的指针,你是否未找到匹配;标志
应与申报1时初始化。trying to write function that returns 1 if every letter in "word" appears in "s". for example: 
containsLetters1("this_is_a_long_string","gas") returns 1
containsLetters1("this_is_a_longstring","gaz") returns 0
containsLetters1("hello","p") returns 0
Can't understand why its not right:
#include <stdio.h> #include <string.h> #define MAX_STRING 100 int containsLetters1(char *s, char *word) { int j,i, flag; long len; len=strlen(word); for (i=0; i<=len; i++) { flag=0; for (j=0; j<MAX_STRING; j++) { if (word==s) { flag=1; word++; s++; break; } s++; } if (flag==0) { break; } } return flag; } int main() { char string1[MAX_STRING] , string2[MAX_STRING] ; printf("Enter 2 strings for containsLetters1\n"); scanf ("%s %s", string1, string2); printf("Return value from containsLetters1 is: %d\n",containsLetters1(string1,string2)); return 0;
解决方案Try these:
for (i=0; i < len; i++)...
(use < instead of <=, since otherwise you would take one additional character);if (word==s)
should beif (*word==*s)
(you compare characters stored at the pointed locations, not pointers);- Pointer s advances, but it should get back to the start of the word
s
, after reaching its end, i.e.s -= len
after thefor (j=...)
;s++
afterword++
is not needed, you advance the pointer by the same amount, whether or not you found a match;flag
should be initialized with 1 when declared.
这篇关于指向字符串C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文