Solved

Need help finding the first vowel, and then setting a variable to the remaining characters

Posted on 2010-11-28
23
486 Views
Last Modified: 2012-05-10
Friends,

I have function/sub that I want to modify.

I want to be able to find the "root" of a name where I find the first vowel, and then capture that vowel and the remaining characters.  

For example, if I have the name "Shirley", I want to capture "irley" and set a variable (root) to that string.

Here is the code I have found, but I need it to work in plain old C.

         NameLength = name.length();
                               //We use a loop to find the first vowel
                              for(i = 0; i < NameLength; i++)
                              {
                              indexchar = testName.substr(i,1);
                              if(indexchar == "a" || indexchar == "e" || indexchar == "i"
                               || indexchar == "o" || indexchar == "u")
                                    {
                                          FirstVowel = i;
                                          break;                //"break" exits the loop it is in
                                    }
                              }
                     / /Now that we know where the first vowel is, we can
                    //select the substring that starts there
                    root = testName.substr(FirstVowel, NameLength - FirstVowel);
           
I am looking for C syntax help specifically!!!

Thanks in advance!
   
#include <ctype.h>

#include <string.h>

#include <stdio.h>

char s;

int i;

int iCounter=0;

char screenName[100]; 

char gameName[100];

char name, root, indexchar; 

int NameLength, FirstVowel; 



char convertlower(char *testName){

      return tolower(*testName);

}

void formatName()

{

      char testName;



      strcpy(gameName, screenName+1); 

      testName = convertlower(screenName);



      //This is where I want insert this code

 

      

            if (testName == 'b' || testName == 'f' || testName == 'm' )

            {

                     switch( testName )

                  {

                  case 'b':

                        printf("%s, %s bo-%s, Banana fanna fo F%s, \n", screenName, screenName, gameName, gameName);

                        printf("Fee fy mo M%s, %s! \n\n", gameName, screenName);

                    break;

                  case 'f':

                        printf("%s, %s bo B%s, Banana fanna fo-%s, \n", screenName, screenName, gameName, gameName);

                        printf("Fee fy mo M%s, %s! \n\n", gameName, screenName);

                  break;

                  case 'm':

                        printf("%s, %s bo B%s, Banana fanna fo F%s, \n", screenName, screenName, gameName, gameName);

                        printf("Fee fy mo-%s, %s! \n\n", gameName, screenName);

                  break;

                  }

            }

            else if(strchr("cdghjklnpqrstvwxz",testName))

            {

                  printf("%s, %s bo B%s, Banana fanna fo F%s, \n", screenName, screenName, gameName, gameName);

                  printf("Fee fy mo M%s, %s! \n\n", gameName, screenName);

            }

            else 

            {

                  printf("%s, %s bo B%s, Banana fanna fo F%s, \n", screenName, screenName, screenName, screenName);

                  printf("Fee fy mo M%s, %s! \n\n", screenName, screenName);

            }

}



int main()

{

	while (i < 3) 

		{

		iCounter++;

		if (iCounter == 1)

		{

			printf ("Hi!  Let's play the name game!!!\n\n");

			printf ( "Type 1 to play, followed by Return...\n" );

			printf ( "Type 2 to exit, followed by Return...\n" );

		}

		else

		{

			printf ("Would you like to play the name game again???\n\n");

			printf ( "Type 1 to play again, followed by Return...\n" );

			printf ( "Type 2 to exit, followed by Return...\n" );

		}

		scanf ("%d", &i);



		

			if (i < 1 || i > 2)   // Sanity check and exit

			break;

			if (i==1)

			{

				printf("Please type your name and then press Return...\n\n");

				scanf ("%s",screenName);

      			formatName();

			}

			else if (i==2)

			{

				break;

			}

		}	



		if ( i == 2 )

		{

		return 0;

		}

}

Open in new window

0
Comment
Question by:indy500fan
  • 11
  • 9
  • 3
23 Comments
 
LVL 32

Expert Comment

by:phoffric
ID: 34227919
You can use strcspn() to find the first vowel (returns the index):
      http://www.cplusplus.com/reference/clibrary/cstring/strcspn/

You can use strpbrk() to find the first vowel (returns a pointer):
     http://www.cplusplus.com/reference/clibrary/cstring/strpbrk/

(See sample code below showing usage of these two functions.)
/* strcspn example */

#include <stdio.h>

#include <string.h>



int main ()

{

  char str[] = "fcba73";

  char keys[] = "1234567890";

  int i;

  i = strcspn (str,keys);

  printf ("The first number in str is at position %d.\n",i+1);

  return 0;

}



/* strpbrk example */

#include <stdio.h>

#include <string.h>



int main ()

{

  char str[] = "This is a sample string";

  char key[] = "aeiou";

  char * pch;

  printf ("Vowels in '%s': ",str);

  pch = strpbrk (str, key);

  while (pch != NULL)

  {

    printf ("%c " , *pch);

    pch = strpbrk (pch+1,key);

  }

  printf ("\n");

  return 0;

}

Open in new window

0
 

Author Comment

by:indy500fan
ID: 34227928
phoffric,

Can you help apply either of these examples to my example, please?  I have no idea where to begin.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34227952
Can you take the code strcspn example and use "Shirley" and return the index i into FirstVowel? Try doing that by morphing the example to suit your purposes. I'll be back in one hour to review what you have posted (inlude the output). If you run into a problem, please ask a specific question along with your post.
0
 
LVL 9

Expert Comment

by:masheik
ID: 34228319
Hi,

         
  NameLength = name.length();
                               //We use a loop to find the first vowel
                              for(i = 0; i < NameLength; i++)
                              {
                              indexchar = testName.substr(i,1);
                              if(indexchar == "a" || indexchar == "e" || indexchar == "i"
                               || indexchar == "o" || indexchar == "u")
                                    {
                                          FirstVowel = i;
                                          break;                //"break" exits the loop it is in
                                    }
                              }
                     / /Now that we know where the first vowel is, we can
                    //select the substring that starts there
                    root = testName.substr(FirstVowel, NameLength - FirstVowel);
           
//I am looking for C syntax help specifically!!!

Open in new window


         1. Here you can use strlen(testStr) instead of getting test.length
             
nameLength = strlen(name);

Open in new window


         2. Use the code you have posted as is
               
  for(i = 0; i < NameLength; i++)
                              {
                              //indexchar = testName.substr(i,1);
 
                            // Modify the indexChar to point to the current postion,
                               indexChar = TestName[i] // Here the name should be a char * or char array like char name[]
                              if(indexchar == "a" || indexchar == "e" || indexchar == "i"
                               || indexchar == "o" || indexchar == "u")
                                    {
                                          FirstVowel = i;
                                          break;                //"break" exits the loop it is in
                                    }
                              }

Open in new window


         3.  You can use an while loop to copy the string required from to end

              say  you have an declaration like char inString[20]; in main
                 
               
                    for(j = firstvowel; j < = nameLength;j++)
                    {
                             inString[j] = TestName[j];
                    }
                             
                  

Open in new window


         now your inString[] contains the irley

         after that you can do whatever you want to do...

0
 

Author Comment

by:indy500fan
ID: 34230837
Okay,

phoffric:  I could try what you are saying, but I still am missing a fundamental piece.  If I plug in "Shirley", yes it would work, but I am trying to set it to the contents of testName, I get an error.

void formatName()
{
            char* inString;
            char testName;
            int i, j;
            int nameLength;
            char name, root, indexchar;
            int FirstVowel;
            char str[];
            char keys[] = "aeiouy";

           testName = convertlower(screenName);
                  str=testName;
                  i = strcspn (str,keys);
                  printf ("The first number in str is at position %d.\n",i+1);

If i do this, it won't compile.  I get the following errors:

Error      1      error C2133: 'str' : unknown size      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      35      project7
Error      2      error C2440: '=' : cannot convert from 'char' to 'char []'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      39      project7
[
masheik:

I tried implementing your suggestion and I get a ton of errors:

Error      1      error C2664: 'strlen' : cannot convert parameter 1 from 'char' to 'const char *'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      38      project7
Error      2      error C2109: subscript requires array or pointer type      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      44      project7
Error      3      error C2446: '==' : no conversion from 'const char *' to 'int'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      45      project7
Error      4      error C2040: '==' : 'int' differs in levels of indirection from 'const char [2]'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      45      project7
Error      5      error C2446: '==' : no conversion from 'const char *' to 'int'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      45      project7
Error      6      error C2040: '==' : 'int' differs in levels of indirection from 'const char [2]'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      45      project7
Error      7      error C2446: '==' : no conversion from 'const char *' to 'int'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      46      project7
Error      8      error C2040: '==' : 'int' differs in levels of indirection from 'const char [2]'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      46      project7
Error      9      error C2446: '==' : no conversion from 'const char *' to 'int'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      46      project7
Error      10      error C2040: '==' : 'int' differs in levels of indirection from 'const char [2]'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      46      project7
Error      11      error C2446: '==' : no conversion from 'const char *' to 'int'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      46      project7
Error      12      error C2040: '==' : 'int' differs in levels of indirection from 'const char [2]'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      46      project7
Error      13      error C2059: syntax error : '='      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      54      project7
Error      14      error C2143: syntax error : missing ';' before ')'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      54      project7
Error      15      error C2143: syntax error : missing ';' before ')'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      54      project7
Error      16      error C2143: syntax error : missing ';' before '{'      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      55      project7
Error      17      error C2109: subscript requires array or pointer type      c:\documents and settings\owner\my documents\visual studio 2008\projects\project7\project7\project7.cpp      56      project7

void formatName()

{

		char* inString;

		char testName;

		int i, j;

		int nameLength;

		char name, root, indexchar; 

		int FirstVowel;



           testName = convertlower(screenName);



	 				 nameLength = strlen(testName);

 							for(i = 0; i < nameLength; i++)

                              {

                              //indexchar = testName.substr(i,1);

 

                            // Modify the indexChar to point to the current postion,

                               indexchar = testName[i]; // Here the name should be a char * or char array like char name[]

                              if(indexchar == "a" || indexchar == "e" || indexchar == "i"

                               || indexchar == "o" || indexchar == "u")

                                    {

                                          FirstVowel = i;

                                          break;                //"break" exits the loop it is in

                                    }

                              }

 



					for(j = FirstVowel; j < = nameLength;j++)

                    {

                             inString[j] = testName[j];

                    }





      //root = name.substr(FirstVowel, NameLength - FirstVowel);

Open in new window

0
 
LVL 9

Expert Comment

by:masheik
ID: 34231127
First thing
Char Testname should be array  like char testname[20]
and also inString[20]
0
 

Author Comment

by:indy500fan
ID: 34231150
masheik,

Nope.  Can you please provide more specific syntax examples if possible.  Pretend I am a beginner (I am), and assume I know nothing (I know nothing).
0
 
LVL 9

Expert Comment

by:masheik
ID: 34231194
And you are missing missing semicolan at the end some where in between the code
0
 

Author Comment

by:indy500fan
ID: 34231244
I don't know, it won't compile.  The examples in this thread will NOT compile because there are issues with how my variables are declared.  That is why I included all my code for the program, because I could simply copy and paste the examples given, and they would work, but not in my example.

I am looking for help with my example.  I do not know C well enough at this point to integrate the examples into my routines.  That is why I am here, and I am looking to the experts.  Please help!
0
 

Author Comment

by:indy500fan
ID: 34232521
Nevermind,

I created this routine and it does what I want:
void lookforFirstVowel()

{

		char testName;

	

		bool exitLoop = false;

		int loopCounter = 0;

         

		strcpy(gameName, screenName); 



		while (exitLoop == false)

		

		{

			loopCounter++;

			testName = convertlower(gameName);

			if (testName == 'a' || testName == 'e' || testName == 'i'|| testName == 'o'|| testName == 'u' )

			{

				//printf("Test1");

				exitLoop = true;

			}

			else

			{

				//printf("Test2");

				strcpy(gameName, screenName+loopCounter); //For Names that don't start with vowels or B, M, or F we trim to the first vowel



			}

		}

}

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 34232971
Accept following two posts:
http:#34227919 showed code in finding the first vowel using standard c library.
http:#34227952 suggests that the author takes this code and modify it and if having trouble with the library call, then ask for further assistance. Author ignored both suggestions. But they represent a valid way to solve the question without having to write the loop code that the author showed.

The author did show new code that had compiler errors but did not follow the suggestions in previous link.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:indy500fan
ID: 34233115
phoffric,

For 500 points (and after I asked for specific syntax help), I guess I was expecting more than I could get from doing a google search.

I did try your "suggestion", but I couldn't get past the errors, and I couldn't get it integrated with my solution?

How was I ignoring your suggestions?  Your suggestions wouldn't work, and the code I presented compiles and works within my environment?  the errors were probably because I didn't have gameName and screenName declared within the function.  I did have their declaration within the sample code that I presented at the beginning.
0
 

Author Comment

by:indy500fan
ID: 34233124
Also, I wasn't asking for a new routine.  I wanted syntax help with the logic provided (because it was already within the parameters of my program).  What you were suggesting, wasn't.  Again, for 500 points, I was looking for specific help.
0
 

Author Comment

by:indy500fan
ID: 34233221
Did you not see that I did in fact try your solution and that it didn't work? see post #34230837
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34233319
Very commendable that you solved the problem yourself. But you closed the question before I came back to address your problems. The suggestion was to first take the example code that shows how to find the first vowel (and then additional) and adapt it to your needs. From your question you indicate a desire to replace one set of libraries (C++) with another. Your solution ingores the suggested library function. Had you followed up on my suggestion, and got that to work, then we could have expanded it to address your next (non-Shirly) point. Then we could have integrated what you have learned in using the c-library function into your application. Using c-library functions in c code is usually the best way to go unless you are a pure beginner.

In fact, we could continue with this suggested route if you wish. Understand that not all contributors are available on a 24x7 basis.
0
 

Author Comment

by:indy500fan
ID: 34233434
phoffric,

If you have a suggestion that I could integrate, I'd be more than happy to continue.  I'm always up for learning.  I just stink at connecting things together the first time.  I need a little more leading if you will.

I hate my solution, but it worked with the limited syntax that I do know.

I am/was just on a time crunch.  I realize that you guys aren't available 24/7 and I realize that you do this as a volunteer; however, if you look at my history, I am generous with points if I get direct answers to my questions.

The participants in this particular forum are all about leading the horse to water, but I'm used to the guys over on the VB.net forum (here at EE), and they operate with a more direct approach.

With that said, what do you have or what is the next step?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34233907
fyi - The C/C++ zone ZA and mods beam us for providing direct solutions for questions that are academic in nature (includes homework as well as self-learning).

Ok then, let's continue. But due to a possible EE bug (it's being looked at), please post all code in the Code box since I am having difficulties copying your code.

1st step: Without adding any of your application, change the strcspn example to demonstrate "Shirley".
2nd step: Modify code in 1st step to use a char array that holds "Shirley".

Once you understand how to use strcspn , then we adjust your lookforFirstVowel() function to use it.
0
 

Author Comment

by:indy500fan
ID: 34234203
okay, I tried the example with Shirley, and I understand (mostly) what is going on.  Much shorter method for getting the location of where the first vowel is.

Now, here is how I worked it into my example:

char screenName[100];

void lookforFirstVowel()
{
      char str[] = screenName; //"Shirley";
      char keys[] = "aeiou";
      int i2;
      i2 = strcspn (str,keys);
      strcpy(gameName, screenName+i2); //For Names that don't start with vowels or B, M, or F we trim to the first vowel
      printf ("The remaining root word is %s.\n",gameName);
}

However, when I do so, I get the following error:

Error      1      error C2440: 'initializing' : cannot convert from 'char [100]' to 'char []'

It's almost like I am trying to put a string into an array.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34234417
Although you can initialize a char array with a string literal, such as "Shirley", you cannot initialize it with another char array.
>>    char str[] = screenName;   // not allowed in C
>>    char str[] = "Shirley";   // OK
One alternative is to not define str at all, and just use screenName in strcspn. Or, you can strncpy() the screenName array after you define the char str[100] array.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34234486
If you want to avoid global variables (usually a good idea), you can change the profile of lookforFirstVowel to pass in the string. If useful, you can return an int to indicate the position of the first vowel.
0
 

Author Comment

by:indy500fan
ID: 34234523
So, it was reduced to:

void lookforFirstVowel()
{
      char keys[] = "aeiou";
      int i2;
      i2 = strcspn (screenName,keys);
      strcpy(gameName, screenName+i2);
}

Now that rocks.

Yeah, I hear what you are saying with respect to globals.  In VB/C# I would use properties.  Does that exist in C?
0
 
LVL 32

Accepted Solution

by:
phoffric earned 500 total points
ID: 34234546
>>  Do properties exist in C
nahh

Even more succinct:

int i2 = strcspn (screenName,keys);

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 34234562
What action do you want to take if the name has no vowels; for example - "Mr.Crptc"
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now