2

I'm trying to convert a Java code I wrote to C, I just started learning C and I confuse it with Java.

My java Code:

public class Biggest 
{
  private static int testsExecuted = 0;
  private static int testsFailed = 0;

  public static void main(String[] args) 
  {
    System.out.println("Testing typical cases, including punctuation\n");
    testLongestWord("the quick brown foxes jumped over the lazy dogs", "jumped");
    testLongestWord("hello world she said", "hello");
    testLongestWord("Hello\tworld\tshe\tsaid", "Hello");
    testLongestWord("HELLO, world she said", "HELLO");
    testLongestWord("hello world! she said???", "hello");
    testLongestWord("\"hello world!\", she said.", "hello");
    testLongestWord("easy as abc123", "abc123");
    testLongestWord("easy as abc,123", "easy");

    System.out.println("\nTesting empty cases\n");
    testLongestWord("", "");
    testLongestWord("!", "");
    testLongestWord(" ", "");
    testLongestWord("\t", "");
    testLongestWord("      ", "");
    testLongestWord("# $ ? % !", "");

    System.out.println("\nTesting edge cases\n");
    testLongestWord("a", "a");
    testLongestWord("abc", "abc");
    testLongestWord("abc d e f ghi", "abc");
    testLongestWord("a a b cc dd abc", "abc");
    testLongestWord("\"a a b cc dd abc.\"", "abc");

    System.out.println("\nTesting apostrophes and dashes\n");
    testLongestWord("this isn't five chars", "chars");
    testLongestWord("this should've been eight chars said the computer", "should've");
    testLongestWord("'this should've been eight chars', said the computer", "should've");
    testLongestWord("'hello world!', she said softly.", "softly");
    testLongestWord("topsy-turvy is a tenletter word", "topsy-turvy");
    testLongestWord("topsy-turvy should not be incorrectly eleven characters", "incorrectly");
    testLongestWord("---in-between-these---", "in-between-these");
    testLongestWord("---in---between---these---", "between");
    testLongestWord("here-is-an-edge-case but a muchmuchlongerword", "muchmuchlongerword");
    testLongestWord("d-o-n't-g-o-o-v-e-r-t-h-e-e-d-g-e with muchmuchlongerwords", "muchmuchlongerwords");
    testLongestWord("two=five-3 isn't three", "three");

    System.out.println("\nThese tests will be opposite in the C version\n");
    testLongestWord("the word antidisestablishmentarianism is very long but not as long as 'Llanfairpwllgwyngyllgogerychwyrndrobwyll-llantysiliogogogoch'.", "Llanfairpwllgwyngyllgogerychwyrndrobwyll-llantysiliogogogoch");
    testLongestWord("the word antidisestablishmentarianism is very long but not as long as 'Llanfairpwllgwyngyllgogerychwyrndrobwyll-llantysiliogogogoch'.", "antidisestablishment");
    testLongestWord("Java strings may contain \0 in the interior", "interior");
    testLongestWord("C strings cannot contain \0 in the interior", "strings");

    System.out.println("\nTotal number of tests executed: " + testsExecuted);
    System.out.println("Number of tests passed:         " + (testsExecuted - testsFailed));
    System.out.println("Number of tests failed:         " + testsFailed);
  }

  public static void testLongestWord(String line, String expected) 
  {
    String result = longestWord(line);

    if (result.equals(expected)) 
    {
      System.out.println("Passed: '" + result + "' from '" + line + "'");
    } 
    else 
    {
      System.out.println("FAILED: '" + result + "' instead of '" + expected + "' from '" + line + "'");
      testsFailed++;
    }

    testsExecuted++;
  }

  public static String longestWord(String line) 
  {
    int pos = 0;
    String longest = "";
    int longestLength = 0;
    String current = "";
    int currentLength = 0;
    char ch;

    line += ' ';
    while (pos < line.length()) 
    {
      ch = line.charAt(pos);

      if ((ch == '\'' || ch == '-') && pos > 0 && 
          Character.isLetter(line.charAt(pos - 1)) && 
          Character.isLetter(line.charAt(pos + 1))) 
      {

        current += ch;

      } 
      else if (Character.isLetterOrDigit(ch)) 
      {

        current += ch;
        currentLength++;

      }
      else 
      {

        if (currentLength > longestLength) 
        {
          longest = current;
          longestLength = currentLength;
        }

        current = "";
        currentLength = 0;

      }

      pos++;
    }

    return longest;
  }
}

My C conversion that I'm working on:

#include <stdio.h>
#include <ctype.h>
#include <string.h>

static int testsExecuted = 0;
static int testsFailed = 0;

char testLongestWord(char line[], char expected[]);
void longestWord(char line[]);

int main(int args, char *argv[]){
    printf("%s\n", "Testing typical cases, including punctuation\n");
    testLongestWord("the quick brown foxes jumped over the lazy dogs", "jumped");
    testLongestWord("hello world she said", "hello");
    testLongestWord("Hello\tworld\tshe\tsaid", "Hello");
    testLongestWord("HELLO, world she said", "HELLO");
    testLongestWord("hello world! she said???", "hello");
    testLongestWord("\"hello world!\", she said.", "hello");
    testLongestWord("easy as abc123", "abc123");
    testLongestWord("easy as abc,123", "easy");


    printf("\n%s\n", "Testing empty cases\n" );
    testLongestWord("", "");
    testLongestWord("!", "");
    testLongestWord(" ", "");
    testLongestWord("\t", "");
    testLongestWord("      ", "");
    testLongestWord("# $ ? % !", "");

    printf("\n%s\n", "Testing edge cases\n" );
    testLongestWord("a", "a");
    testLongestWord("abc", "abc");
    testLongestWord("abc d e f ghi", "abc");
    testLongestWord("a a b cc dd abc", "abc");
    testLongestWord("\"a a b cc dd abc.\"", "abc");


    printf("\n%s\n", "Testing apostrophes and dashes\n" );
    testLongestWord("this isn't five chars", "chars");
    testLongestWord("this should've been eight chars said the computer", "should've");
    testLongestWord("'this should've been eight chars', said the computer", "should've");
    testLongestWord("'hello world!', she said softly.", "softly");
    testLongestWord("topsy-turvy is a tenletter word", "topsy-turvy");
    testLongestWord("topsy-turvy should not be incorrectly eleven characters", "incorrectly");
    testLongestWord("---in-between-these---", "in-between-these");
    testLongestWord("---in---between---these---", "between");
    testLongestWord("here-is-an-edge-case but a muchmuchlongerword", "muchmuchlongerword");
    testLongestWord("d-o-n't-g-o-o-v-e-r-t-h-e-e-d-g-e with muchmuchlongerwords", "muchmuchlongerwords");
    testLongestWord("two=five-3 isn't three", "three");

    printf("\n%s\n", "These tests will be opposite in the C version\n");
    testLongestWord("the word antidisestablishmentarianism is very long but not as long as 'Llanfairpwllgwyngyllgogerychwyrndrobwyll-llantysiliogogogoch'.", "Llanfairpwllgwyngyllgogerychwyrndrobwyll-llantysiliogogogoch");
    testLongestWord("the word antidisestablishmentarianism is very long but not as long as 'Llanfairpwllgwyngyllgogerychwyrndrobwyll-llantysiliogogogoch'.", "antidisestablishment");
    testLongestWord("Java strings may contain \0 in the interior", "interior");
    testLongestWord("C strings cannot contain \0 in the interior", "strings");

    printf("Total number of test executed:  %d\n", testsExecuted );
    printf("number of test passed:  %d\n", (testsExecuted - testsFailed));
    printf("Number of test failed: %d\n", testsFailed );

    //longestWord("Java strings may contain \0 in the interior");

}

char testLongestWord(char line[], char expected[]){
    char result[200];

    /*longestWord(line);*/
    strcpy(result, line);
    //char *result = longestWord(line);
    //printf("%s\n", line );
    //int ret = strcmp(result,expected);

    if(strcmp(result,expected)){ // function returns 0 if they are equal
        printf("passed: '%s' from '%s'\n", result, line);
    }else{
        printf("FAILED: '%s' from '%s'\n", expected, result);
        testsFailed++;
    }
    testsExecuted++;
    return 0;

}


void longestWord(char line[]){
    char longest[200];

    int pos = 0;
    int longestLength = 0;
    char current[300];
    int currentLength = 0;
    char ch;
    size_t maxPos = strlen(line);

    while(pos < maxPos){
        ch = line[pos++];
        for(pos = 0; pos < maxPos;pos++){
            ch = line[pos++];
            if((ch == '\'' || ch == '-') && (pos > 0) && isalpha(line[pos-1]) && isalpha(line[pos+1])){
                strcpy(current, &ch);
            }else if(isalpha(ch) || isdigit(ch)){
                strcpy(current, &ch);
                currentLength++;
                //printf("%s\n", longest );

            }else{
                if(currentLength > longestLength){
                    strcpy(longest,current);
                    longestLength = currentLength;
                }
                //strcpy(current, "");
                currentLength =0;
            }
        }

    }

}

The errors and warnings i'm getting EDIT: I'm no longer having these errors.

I'm having problems with this line String result = longestWord(line); in java to c, the function longestWords is not transferring the result to result. Is there a way to do it?

2
  • 2
    Most of the issues you have got there are just basics of C. Perhaps, reading a textbook would help (before blindly converting Java code to C). Commented Jan 31, 2016 at 12:16
  • Apart from the syntactical differences, why are you trying to assign the result of a function returning char to an array of char? This wouldn't be valid in Java either. And what's with the hidden "thanks"? Commented Jan 31, 2016 at 12:22

2 Answers 2

1

There's a lot wrong there about conflating arrays and pointers in C and there's no single thing I could point at and say that if you changed it then everything would start working or even that you'd see how to move forward.

You need to take a step back and start learning C concepts - particularly how pointers and arrays work in C, and how to safely move between the two. Only when you really understand how C treats memory, and how to write a correct C program from first principles, can you start thinking about how to convert a working Java program into a working C program.

Try this answer for more information - Tutorial on C pointers and arrays from a Java standpoint

Sign up to request clarification or add additional context in comments.

Comments

1

Setting a C string into a character array like this

char result[] = <something>;

is allowed only when <something> is fully known at compile time, i.e. when it is

  • a string literal, i.e. a sequence of characters in double quotes, or
  • an array initializer, i.e. a list of characters in curly braces.

In your case you should use char *, a pointer to character, because that is what your longestWord function should return according to the logic of your code (see below for a solution):

char *result = longestWord(line);

As far as the "implicitly declared" errors go, all you need to do is to add missing header files with #include at the top of your code.

Once your program starts compiling, it is going to exhibit undefined behavior (i.e. crash randomly, or perhaps not so randomly) because your code attempts to write into memory of string literals. For example

strcat(line, " ");

would try to append a space to the sentence passed in from the original call. Since the sentence is a string literal, writing to it is disallowed.

Also there is no easy way to return a C string from a function without using dynamic memory allocation. A better approach is to pass the buffer for the longest word from the caller, and fill it in inside the function, like this:

void longestWord(char line[], char longestBuf[], size_t bufSize)

The caller must provide a writable char[] array of sufficient length, into which the result should be written.

5 Comments

Actually longestWord returns char; perhaps OP was looking for a String type in C and decided this was what they wanted.
@szczurcio You are right, there's a lot more to fix in this conversion than meets the eye initially. Thanks!
I don't understand your idea of changing the char function to void longestWord(char line[], char longest[]) and passing buffers can you give explain clearer in an example or give a link to a documentation?
@T-- This answer (more specifically, its last example, which uses calculateMonths(3, month, sizeof(month)) call) provides a very good explanation of the approach.
I used char *result = longestWord(line); but line doesn't seem to be sending its result to result my longest word function is now void longestWord(char line[])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.