1 / 1 / 1
Регистрация: 26.11.2011
Сообщений: 33
1

Вывести все слова, в которых есть буква "a"

29.11.2011, 17:37. Показов 10334. Ответов 69
Метки нет (Все метки)

не могу найти ошибку
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int i=0,j=0,a=0,schet=0;
char s[50],s1[50];
     cin.getline(s,50);
             while(i<50)
{
                        if((isspace(s[i])) && (isalnum(s[i-1])))
{    
     j=i-1;schet=0;
             while((!isspace(s[j])) || (s[j]=='\n'))
{    
     j--;
                        if(s[j]=='a')
     schet++;
     }
             for(j;j<i+1;j++)
{
                        if(schet>=1)
     s1[j]=s[j];
}
 
}
    i++;
}cout<<s1<<endl;
getch();
нужно вывести все слова в которых есть буква a

Добавлено через 2 часа 30 минут
помогите пожалуйста...
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
29.11.2011, 17:37
Ответы с готовыми решениями:

Найти все и вывести все слова в которых есть буква "к"
дана строка (ввод с клавы) найти все и вывести все слова в которых есть буква...

Вывести все слова, в которых первая буква "а"
Вывести все слова, в которых первая буква &quot;а&quot;. Нужно сделать через посимвольную обработку. Не...

Все слова, в которых буква "а" встречается более 2х раз, удалить из текста. Вывести полученную строку на экран
Помогите, пожалуйста решить данную задачу: Все слова, в которых буква &quot;а&quot; встречается более 2х...

Удалить из текста все слова в которых буква "а" встречается более двух раз
Все слова, в которых буква &quot;а&quot; встречается более 2-х раз, удалить из текста. Вывести полученную...

69
Каратель
Эксперт С++
6607 / 4026 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
29.11.2011, 17:50 2
mister pOO, сначала strtok-ом разбиваем строку на слова, а потом проверяем наличие буквы в них
0
Эксперт С++
5038 / 2617 / 241
Регистрация: 07.10.2009
Сообщений: 4,310
Записей в блоге: 1
29.11.2011, 17:51 3
http://liveworkspace.org/code/... 0bc2e541d1
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <array>
 
int main() {
   std::array<std::string, 5> words = {
      "abra", "kfghfff", "erjha", "toejhnaerbna", "fuf"
   };
   
   for (const std::string &word : words) {
      size_t founded = word.find_first_of('a');
      if (founded != std::string::npos) {
         std::cout << word << std::endl;
      }
   }
   
   return 0;
}
http://liveworkspace.org/code/... ba8db8fced
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <string.h>
 
#define NWORDS 5
 
int main() {
   size_t i = 0;  
   const char *ptr = NULL;
   const char *words[] = {
      "abra", "kfghfff", "erjha", "toejhnaerbna", "fuf"
   };
   
   for (i = 0; i < NWORDS; ++i) {
      if ((ptr = strchr(words[i], 'a')) != NULL) {
         printf("%s ", words[i]);
      }
   }
   
   return 0;
}
http://liveworkspace.org/code/... efbada5473
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <string.h>
 
#define NWORDS 5
 
int main() {
   size_t i = 0;  
   size_t j = 0;
   size_t len = 0;
 
   const char *words[] = {
      "abra", "kfghfff", "erjha", "toejhnaerbna", "fuf"
   };
   
   for (i = 0; i < NWORDS; ++i) {
      len = strlen(words[i]);
      for (j = 0; j < len; ++j) {
         if (words[i][j] == 'a') {
            printf("%s ", words[i]);
            break;
         }
      }
   }
   
   return 0;
}
0
Заблокирован
29.11.2011, 18:36 4
Цитата Сообщение от Jupiter Посмотреть сообщение
mister pOO, сначала strtok-ом разбиваем строку на слова, а потом проверяем наличие буквы в них
как такая альтернатива?
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char *str = "how to use manpages in programming";
    char *p = str, *wrdbeg;
 
    puts(str);
    str = strchr(str, 'a');
 
    if (str)
    {
        while (str)
        {
            wrdbeg = str;
            while ( ( wrdbeg != p ) && ( *(wrdbeg - 1) != ' ') )
                --wrdbeg;
            while( ( *str != 0 ) && ( *(str + 1) != ' ') )
                ++str;
            while ( wrdbeg != str )
                putchar( *( wrdbeg++ ) );
            putchar('\n');
            str = strchr(str, 'a');
        }
    }
    else
        puts("symbol 'a' is not found");
 
    return 0;
}
0
Каратель
Эксперт С++
6607 / 4026 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
29.11.2011, 18:52 5
Цитата Сообщение от alkagolik Посмотреть сообщение
как такая альтернатива?
буквочку теряет http://codepad.org/Ys6pjkMx
0
go
Эксперт С++
3646 / 1378 / 243
Регистрация: 16.04.2009
Сообщений: 4,526
29.11.2011, 18:55 6
fasked, то разделение на слова нужно делать самому, а то сводите все к
C
1
2
if (strstr (words[i],"a") )
        printf ("\n%s", words[i]);
0
Заблокирован
29.11.2011, 18:56 7
непорядок
0
Эксперт С++
4264 / 2238 / 203
Регистрация: 26.08.2011
Сообщений: 3,802
Записей в блоге: 5
29.11.2011, 18:56 8
fasked, функция strchr не очень быстрая и зависит от длины строки (первый параметр), функция strtok содержит внутри себя strchr, поэтому тоже не очень быстрая функция + портит строку. Но это вы сами прекрасно знаете, просто для тех, кому это интересно, реально писать без strchr и strtok свои функции в разы быстрее, при определенных раскладах и в десятки раз быстрее
0
Заблокирован
29.11.2011, 19:18 9
Thinker, вполне разделяю, только боюсь что такая реализация вызовет сомнения.
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <string.h>
 
char *my_strchr(const char *s, char x)
{
    register char *c = s;
    while( (*c != x) && (*c != 0) )
        ++c;
 
    return ( *c == 0 ) ? 0 : c;
}
 
int main(void)
{
    char *str = "how to use manpages in programming";
    char *p = str, *wrdbeg;
 
    puts(str);
    str = my_strchr(str, 'a');
 
    if (str)
    {
        while (str)
        {
            wrdbeg = str;
            while ( ( wrdbeg != p ) && ( *(wrdbeg - 1) != ' ') )
                --wrdbeg;
            while( ( *str != 0 ) && ( *str != ' ') )
                ++str;
            while ( wrdbeg != str )
                putchar( *( wrdbeg++ ) );
            putchar('\n');
            str = my_strchr(str, 'a');
        }
    }
    else
        puts("symbol 'a' is not found");
 
    return 0;
}
0
Эксперт С++
4264 / 2238 / 203
Регистрация: 26.08.2011
Сообщений: 3,802
Записей в блоге: 5
29.11.2011, 19:25 10
alkagolik, вы пошли тем же путем, что и программисты, написавшие strchr. С учетом ассемблерных вставок, функция strchr будет работать раза в полтора быстрее вашей функции my_strchr.
0
Заблокирован
29.11.2011, 19:25 11
вот только не разделяю что она зависит от длины строки.
0
Эксперт С++
4264 / 2238 / 203
Регистрация: 26.08.2011
Сообщений: 3,802
Записей в блоге: 5
29.11.2011, 19:26 12
Цитата Сообщение от alkagolik Посмотреть сообщение
вот только не разделяю что она зависит от длины строки.
Зависит, поверьте. Чем длиннее строка, тем в среднем больше проверок.
0
Заблокирован
29.11.2011, 19:28 13
Thinker, нет, не тем же, реальная функция организована циклом с постусловем и проверкой в теле цикла. Асм это уже перебор мне кажется.

Добавлено через 41 секунду
Цитата Сообщение от Thinker Посмотреть сообщение
Зависит, поверьте. Чем длиннее строка, тем в среднем больше проверок.
именно этим моя реализация и отличается
0
Эксперт С++
4264 / 2238 / 203
Регистрация: 26.08.2011
Сообщений: 3,802
Записей в блоге: 5
29.11.2011, 19:31 14
Цитата Сообщение от alkagolik Посмотреть сообщение
Thinker, нет, не тем же, реальная функция организована циклом с постусловем и проверкой в теле цикла. Асм это уже перебор мне кажется.
Проверьте на скорость, если не верите. Если ваша функция хотя бы по времени столько же будет работать, то это уже хорошо.

Добавлено через 2 минуты
Цитата Сообщение от alkagolik Посмотреть сообщение
именно этим моя реализация и отличается
В смысле? ваша функция в среднем случае пробегает по строке s примерно strlen(s)/2. Функция strchr построена по такому же принципу.
0
Заблокирован
29.11.2011, 19:54 15
Цитата Сообщение от Thinker Посмотреть сообщение
В смысле? ваша функция в среднем случае пробегает по строке s примерно strlen(s)/2
немного не понял, вы предлагаете за один проход найти сразу все символы? Насчет вставок асма не знаю как там они все согласованы с ОСапи и компиляторами разных версий, а в целом можно и так реализовать
C
1
2
3
4
5
6
7
8
9
10
char *my_strchr(s, x)
register char *s;
register char x;
{
 
    if ( *s )
        return (*s == x) ? s : my_strchr(s + 1, x);
    else
        return 0;
}
0
Эксперт С++
4264 / 2238 / 203
Регистрация: 26.08.2011
Сообщений: 3,802
Записей в блоге: 5
29.11.2011, 20:15 16
alkagolik, рекурсия не решает проблему. У вас хорошая функция, но я бы в одну строчку написал:

C
1
2
3
4
char *my_strchr(char *s, char c)
{
   return *s ? (*s == c ? s : my_strchar(s+1, c)) : NULL;
}
Если задача такая, что требуется в строке s определить, например, сколько символов принадлежит строке t, то я против использования strchr. Также против использования функции strtok при выделении слов из строки, но это сугубо мое мнение, НО если текст немаленький (например, тысячи строк, каждая из которых по не менее тысячи или миллионы символов), то эффект от отказа strtok ОГРОМЕН
0
Заблокирован
29.11.2011, 20:21 17
Thinker, я просто принципиально не придерживаюсь такого стиля. На мой взгляд это нечитабельно (не в данном случае, а в более длинных сочетаниях) и просто обязано содержать длинный комментарий, но это имхо. В принципе тут смотря какой подход к задаче выбрать. Думаю что нет смысла считать количество нужных символов, а потом делить на слова (опять же используя поиск пробела, знаков препинания в качестве разделителя). Правильнее будет найти символ и построить от него слово, это опять же имхо. Кстати знаки препинания я как раз и не учел в программе.
0
Эксперт С++
4264 / 2238 / 203
Регистрация: 26.08.2011
Сообщений: 3,802
Записей в блоге: 5
29.11.2011, 20:24 18
alkagolik, я уже не о задаче из данного топика, а о том, что функции strchr и strtok медленные. В посте выше я написал в каких задачах эти функции лучше не использовать
0
Эксперт С++
5038 / 2617 / 241
Регистрация: 07.10.2009
Сообщений: 4,310
Записей в блоге: 1
29.11.2011, 20:24 19
Цитата Сообщение от Thinker Посмотреть сообщение
функция strchr не очень быстрая и зависит от длины строки (первый параметр)
Функция strchr очень быстрая.
glibc strchr

-- Function: char * strchr (const char *STRING, int C)
The `strchr' function finds the first occurrence of the character
C (converted to a `char') in the null-terminated string beginning
at STRING. The return value is a pointer to the located
character, or a null pointer if no match was found.

For example,
strchr ("hello, world", 'l')
=> "llo, world"
strchr ("hello, world", '?')
=> NULL

The terminating null character is considered to be part of the
string, so you can use this function get a pointer to the end of a
string by specifying a null character as the value of the C
argument. It would be better (but less portable) to use
`strchrnul' in this case, though.

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/* Copyright (C) 1991,1993-1997,1999,2000,2003,2006
   Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   Based on strlen implementation by Torbjorn Granlund (tege@sics.se),
   with help from Dan Sahlin (dan@sics.se) and
   bug fix and commentary by Jim Blandy (jimb@ai.mit.edu);
   adaptation to strchr suggested by **** Karpinski (****@cca.ucsf.edu),
   and implemented by Roland McGrath (roland@ai.mit.edu).
 
   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
 
   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
 
   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA.  */
 
#include <string.h>
#include <memcopy.h>
#include <stdlib.h>
 
#undef strchr
 
/* Find the first occurrence of C in S.  */
char *
strchr (s, c_in)
     const char *s;
     int c_in;
{
  const unsigned char *char_ptr;
  const unsigned long int *longword_ptr;
  unsigned long int longword, magic_bits, charmask;
  unsigned reg_char c;
 
  c = (unsigned char) c_in;
 
  /* Handle the first few characters by reading one character at a time.
     Do this until CHAR_PTR is aligned on a longword boundary.  */
  for (char_ptr = (const unsigned char *) s;
       ((unsigned long int) char_ptr & (sizeof (longword) - 1)) != 0;
       ++char_ptr)
    if (*char_ptr == c)
      return (void *) char_ptr;
    else if (*char_ptr == '\0')
      return NULL;
 
  /* All these elucidatory comments refer to 4-byte longwords,
     but the theory applies equally well to 8-byte longwords.  */
 
  longword_ptr = (unsigned long int *) char_ptr;
 
  /* Bits 31, 24, 16, and 8 of this number are zero.  Call these bits
     the "holes."  Note that there is a hole just to the left of
     each byte, with an extra at the end:
 
     bits:  01111110 11111110 11111110 11111111
     bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
 
     The 1-bits make sure that carries propagate to the next 0-bit.
     The 0-bits provide holes for carries to fall into.  */
  switch (sizeof (longword))
    {
    case 4: magic_bits = 0x7efefeffL; break;
    case 8: magic_bits = ((0x7efefefeL << 16) << 16) | 0xfefefeffL; break;
    default:
      abort ();
    }
 
  /* Set up a longword, each of whose bytes is C.  */
  charmask = c | (c << 8);
  charmask |= charmask << 16;
  if (sizeof (longword) > 4)
    /* Do the shift in two steps to avoid a warning if long has 32 bits.  */
    charmask |= (charmask << 16) << 16;
  if (sizeof (longword) > 8)
    abort ();
 
  /* Instead of the traditional loop which tests each character,
     we will test a longword at a time.  The tricky part is testing
     if *any of the four* bytes in the longword in question are zero.  */
  for (;;)
    {
      /* We tentatively exit the loop if adding MAGIC_BITS to
     LONGWORD fails to change any of the hole bits of LONGWORD.
 
     1) Is this safe?  Will it catch all the zero bytes?
     Suppose there is a byte with all zeros.  Any carry bits
     propagating from its left will fall into the hole at its
     least significant bit and stop.  Since there will be no
     carry from its most significant bit, the LSB of the
     byte to the left will be unchanged, and the zero will be
     detected.
 
     2) Is this worthwhile?  Will it ignore everything except
     zero bytes?  Suppose every byte of LONGWORD has a bit set
     somewhere.  There will be a carry into bit 8.  If bit 8
     is set, this will carry into bit 16.  If bit 8 is clear,
     one of bits 9-15 must be set, so there will be a carry
     into bit 16.  Similarly, there will be a carry into bit
     24.  If one of bits 24-30 is set, there will be a carry
     into bit 31, so all of the hole bits will be changed.
 
     The one misfire occurs when bits 24-30 are clear and bit
     31 is set; in this case, the hole at bit 31 is not
     changed.  If we had access to the processor carry flag,
     we could close this loophole by putting the fourth hole
     at bit 32!
 
     So it ignores everything except 128's, when they're aligned
     properly.
 
     3) But wait!  Aren't we looking for C as well as zero?
     Good point.  So what we do is XOR LONGWORD with a longword,
     each of whose bytes is C.  This turns each byte that is C
     into a zero.  */
 
      longword = *longword_ptr++;
 
      /* Add MAGIC_BITS to LONGWORD.  */
      if ((((longword + magic_bits)
 
        /* Set those bits that were unchanged by the addition.  */
        ^ ~longword)
 
       /* Look at only the hole bits.  If any of the hole bits
          are unchanged, most likely one of the bytes was a
          zero.  */
       & ~magic_bits) != 0 ||
 
      /* That caught zeroes.  Now test for C.  */
      ((((longword ^ charmask) + magic_bits) ^ ~(longword ^ charmask))
       & ~magic_bits) != 0)
    {
      /* Which of the bytes was C or zero?
         If none of them were, it was a misfire; continue the search.  */
 
      const unsigned char *cp = (const unsigned char *) (longword_ptr - 1);
 
      if (*cp == c)
        return (char *) cp;
      else if (*cp == '\0')
        return NULL;
      if (*++cp == c)
        return (char *) cp;
      else if (*cp == '\0')
        return NULL;
      if (*++cp == c)
        return (char *) cp;
      else if (*cp == '\0')
        return NULL;
      if (*++cp == c)
        return (char *) cp;
      else if (*cp == '\0')
        return NULL;
      if (sizeof (longword) > 4)
        {
          if (*++cp == c)
        return (char *) cp;
          else if (*cp == '\0')
        return NULL;
          if (*++cp == c)
        return (char *) cp;
          else if (*cp == '\0')
        return NULL;
          if (*++cp == c)
        return (char *) cp;
          else if (*cp == '\0')
        return NULL;
          if (*++cp == c)
        return (char *) cp;
          else if (*cp == '\0')
        return NULL;
        }
    }
    }
 
  return NULL;
}
 
#ifdef weak_alias
#undef index
weak_alias (strchr, index)
#endif
libc_hidden_builtin_def (strchr)

Было бы глупо иметь зависимость от длины строки, если надо найти лишь первое совпадение.
Цитата Сообщение от Thinker Посмотреть сообщение
функция strtok содержит внутри себя strchr
А вот и неправда.
Код
fasked@k50id:~/src/glibc/string> cat strtok.c | grep strchr
fasked@k50id:~/src/glibc/string>
glibc strtok
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* Copyright (C) 1991,1996,1997,1999,2000,2001,2007
   Free Software Foundation, Inc.
   This file is part of the GNU C Library.
 
   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
 
   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
 
   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA.  */
 
#include <string.h>
 
 
static char *olds;
 
#undef strtok
 
/* Parse S into tokens separated by characters in DELIM.
   If S is NULL, the last string strtok() was called with is
   used.  For example:
    char s[] = "-abc-=-def";
    x = strtok(s, "-");     // x = "abc"
    x = strtok(NULL, "-=");     // x = "def"
    x = strtok(NULL, "=");      // x = NULL
        // s = "abc\0=-def\0"
*/
char *
strtok (s, delim)
     char *s;
     const char *delim;
{
  char *token;
 
  if (s == NULL)
    s = olds;
 
  /* Scan leading delimiters.  */
  s += strspn (s, delim);
  if (*s == '\0')
    {
      olds = s;
      return NULL;
    }
 
  /* Find the end of the token.  */
  token = s;
  s = strpbrk (token, delim);
  if (s == NULL)
    /* This token finishes the string.  */
    olds = __rawmemchr (token, '\0');
  else
    {
      /* Terminate the token and make OLDS point past it.  */
      *s = '\0';
      olds = s + 1;
    }
  return token;
}
strspn и strpbrk тоже не содержат в себе strchr.
0
Эксперт С++
4264 / 2238 / 203
Регистрация: 26.08.2011
Сообщений: 3,802
Записей в блоге: 5
29.11.2011, 20:26 20
Цитата Сообщение от alkagolik Посмотреть сообщение
Thinker, я просто принципиально не придерживаюсь такого стиля.
Это вы о моей рекурсивной функции? Тогда дело вкуса Но для поиска символов в строке я так бы и сам не писал
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
29.11.2011, 20:26
Помогаю со студенческими работами здесь

Написать программу,которая находит все слова,в которых буква "а" встречается больше чем один раз.
Есть строка,которая состоит из слов,разделенных любым количеством промежутков.Написать...

Найти все слова, в которых есть двойные согласные, и заменить их символом "*"
дан текст(на англ. яз). найти все слова, в которых есть двойные согласные и заменить их *.

Удалить столбцы символьной матрицы, в которых есть буква "А"
И удалить все столбцы в которых есть буква &quot;А&quot;

Найти слова в которых буква "т" встречается чаще чем в остальних
Здраствуйте. Помогите, пожалуйста, сделать программу. Нужно ,используя строки (string),ввести...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru