简体   繁体   English

如何在java中定义一个没有长度的字符串数组?

[英]How to define a string array without length in java?

I'm confused about a simple question.我对一个简单的问题感到困惑。 Can you tell me how to define a string array without length?你能告诉我如何定义一个没有长度的字符串数组吗? Because I can't find any information about this question.因为我找不到有关此问题的任何信息。 if I write String[] str=new String[];如果我写String[] str=new String[]; or String[] str=new String[]{};String[] str=new String[]{}; they will have error.他们会有错误。 But why?但为什么? Thx!!!谢谢!!!

Here is my homework: write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word.这是我的作业:编写一个程序从命令行参数中读取一系列单词,并找到给定单词的第一个匹配项的索引。 For example,java First Match lady That young lady looks after the old lady.例如,java First Match Lady 那个年轻的女士照顾老太太。 would find the index for the first match of “lady” in the sentence “That young lady looks after the old lady”, and display the index of its first occurrence in the sentence on console, eg,“The index of the first match of 'lady'is 2”.会在“那个年轻的女士照顾老太太”这句话中找到“女士”的第一个匹配的索引,并在控制台上显示它在句子中第一次出现的索引,例如,“第一个匹配的索引” '女士'是 2”。

Here is my code:这是我的代码:

String[] str=new String[11];
        int a=0;
        for(int i=0;i<11;i++){
            str[i] = args[a];
            a++;
        }

In your case, you can count the number of args as follows:在您的情况下,您可以按如下方式计算 args 的数量:

int argsCount = args.length;

You can then create you array as follows:然后,您可以按如下方式创建数组:

String [] str = new String[argsCount - 1];

You can then fill the strings array with the words and search the array to find the first argument passed to your programs然后,您可以用单词填充字符串数组并搜索数组以找到传递给程序的第一个参数

If you must use an array that can be resized, you should use LinkedList https://www.tutorialspoint.com/java/java_linkedlist_class.htm如果必须使用可以调整大小的数组,则应使用 LinkedList https://www.tutorialspoint.com/java/java_linkedlist_class.htm

Arrays are fixed length data structures in Java.数组是 Java 中固定长度的数据结构。 When you instantiate it you must either define size of array for example:当您实例化它时,您必须定义数组的大小,例如:

String [] myString = new String [5];

Or you should instantiate it with its members.或者你应该用它的成员实例化它。

String []myStringArray = new String []{"first","second"};

If you do not know how many elements you will get, use ArrayList instead.如果您不知道将获得多少个元素,请改用 ArrayList。 Size of an ArrayList can increase or decrease at runtime dynamically. ArrayList 的大小可以在运行时动态增加或减少。 You can look at this question for more information about ArrayLists.您可以查看此问题以获取有关 ArrayLists 的更多信息。

Requirements:要求:

  • First command line argument is the word to search for第一个命令行参数是要搜索的词
  • Other arguments is a space separated list forming a sentence其他参数是一个空格分隔的列表,形成一个句子
  • Program should return the index of the first argument in the other arguments程序应该返回其他参数中第一个参数的索引

Sample implementation:示例实现:

public static void main(String[] args)
{
    // Check whether min. one argument is provided.
    if (args.length == 0)
    {
        System.err.println("No arguments provided");
        System.err.println("Usage: <match> <word1> <word2> [...]");
        return;
    }

    // First argument is the word to search for.
    String match = args[0];

    // Iterate the other arguments to find a match.
    for (int i = 1; i < args.length; i++)
    {
        if (match.equals(args[i]))
        {
            // The first argument is the word to search for: Substract index by 1.
            System.out.printf("The index of the first match of '%s' is %d\n", match, (i - 1));
            return;
        }
    }

    System.out.printf("No match of '%s' found\n", match);
}

You should specify the length of an array when you allocate memory for it , but this is not required when you declare it.应该在为数组分配内存时指定它的长度,但是在声明它时这不是必需的。 The reason is that JVM should know how much memory should be allocted before allocating memory for the array.原因是JVM在为数组分配内存之前应该知道应该分配多少内存。

So I think ecen though you can declare an array without length, but you can't actually use the array before you specify the amount of memory that you need.所以我认为 ecen 虽然您可以声明一个没有长度的数组,但是在指定所需的内存量之前,您实际上不能使用该数组。

To solve this problem, people developed ArrayList .为了解决这个问题,人们开发了ArrayList ArrayList does not require the size of the array. ArrayList不需要数组的大小。 All you have to do is:您所要做的就是:

ArrayList<String> array=new ArrayList<String>();
for(int i=0;i<args.length;++i)
{
    array.add(args[i]);
}

To convert the ArrayList to String[] array, use this.要将ArrayList转换为 String[] 数组,请使用它。

String [] arrarray=new String[array.size()];
arrarray=array.toArray(arrarray);

If you want a String[] with 0 length:如果你想要一个长度为0String[]

String[] test = new String[0];

And then然后

System.out.println(test.length);

will give you会给你

0

EDIT编辑

The asker's question was "how to define a string array without length in Java.提问者的问题是“如何在 Java 中定义一个没有长度的字符串数组。

To answer the asker's entire problem, "write a program that reads a series of words from the command line and find the index of the first match of a given word", two simple methods are needed.要回答提问者的整个问题,“编写一个程序,从命令行读取一系列单词并找到给定单词的第一个匹配项的索引”,需要两种简单的方法。

One method to read in the argments, and another method to find the appropriate index.一种方法是读入参数,另一种方法是找到合适的索引。

If the asker is using the String[] args of the main method for this, the problem is reduced to just one method (finding the index of the word they're looking for).如果提问者为此使用了main方法的String[] args ,问题就简化为一种方法(找到他们正在寻找的单词的索引)。

for example例如

public static int findIndex(String term, String[] args) {
    int index = -1;

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals(term)) {
            index = i;
            break;
        }
    }

    return index;
}

and therefore, if the asker has a list of words that come in from the main method,因此,如果提问者有一个来自 main 方法的单词列表,

findIndex("lady", args);

will return the index.将返回索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM