指向字符串C [英] Pointers to string C

查看:117
本文介绍了指向字符串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;


解决方案

尝试这些:


  1. 为(i = 0; I< LEN,我++)... (使用<而非< =,否则你会采取一个额外的字符);

  2. 如果(字== S)如果(*字== * S)(你比较存储在尖的位置,而不是指针)字符;

  3. 指针小号的进步,但它应该得到回字取值,达到其目的,即在 S的开始 - = LEN 为(J = ...);

  4. 取值++ 字++ 后是不需要的,你按相同的量超前的指针,你是否未找到匹配;

  5. 标志应与申报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:

  1. for (i=0; i < len; i++)... (use < instead of <=, since otherwise you would take one additional character);
  2. if (word==s) should be if (*word==*s) (you compare characters stored at the pointed locations, not pointers);
  3. Pointer s advances, but it should get back to the start of the word s, after reaching its end, i.e. s -= len after the for (j=...);
  4. s++ after word++ is not needed, you advance the pointer by the same amount, whether or not you found a match;
  5. flag should be initialized with 1 when declared.

这篇关于指向字符串C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆