错误将java代码转换为字符串 - 传递函数的结果

时间:2016-01-31 12:11:46

标签: java c

我正在尝试将我编写的Java代码转换为C,我刚开始学习C并且我将它与Java混淆。

我的java代码:

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;
  }
}

我正在进行的我的C转换:

#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;
            }
        }

    }

}

错误和警告我正在编辑:我不再有这些错误了。

我在java到c中遇到这行String result = longestWord(line);的问题,函数longestWords没有将结果传递给结果。有办法吗?

2 个答案:

答案 0 :(得分:1)

关于在C中混淆数组和指针有很多错误,并且没有任何一件事我可以指出并说如果你改变了它,那么一切都会开始工作,甚至你会看到如何继续前进。

你需要后退一步并开始学习C概念 - 特别是指针和数组如何在C中工作,以及如何安全地在两者之间移动。只有当你真正理解C如何处理内存,以及如何从第一原则编写正确的C程序时,你才能开始考虑如何将一个有效的Java程序转换为一个可用的C程序。

尝试此答案以获取更多信息 - Tutorial on C pointers and arrays from a Java standpoint

答案 1 :(得分:1)

将C字符串设置为像这样的字符数组

char result[] = <something>;
只有在编译时完全知道<something>时才允许

,即

  • 字符串文字,即双引号中的字符序列,或
  • 数组初始值设定项,即大括号中的字符列表。

在您的情况下,您应该使用char *,一个指向字符的指针,因为这是您的longestWord函数应根据代码的逻辑返回的内容(请参阅下面的解决方案):

char *result = longestWord(line);

就“隐式声明”错误而言,您需要做的就是在代码顶部添加#include的缺少的头文件。

一旦你的程序开始编译,它将展示未定义的行为(即随机崩溃,或者可能不是随机的),因为你的代码试图写入字符串文字的内存。例如

strcat(line, " ");

会尝试在原始调用中传入的句子中添加空格。由于句子是字符串文字,因此不允许写入。

此外,没有简单的方法可以在不使用动态内存分配的情况下从函数返回C字符串。更好的方法是将缓冲区传递给调用者的最长单词,并将其填入函数内部,如下所示:

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

调用者必须提供一个足够长度的可写char[]数组,并在其中写入结果。