How to return a 2D String

how to return a 2d array in c
how to return a 2d array in c++
return pointer to 2d array c
how to return a string in c
return a matrix in c
return value 2d array
return 2d char array c
method return 2d array

I do not fully understand how to return a 2D object. So I wrote a method that takes in an input with a document and I have to return a list of all unique words in it and their number of occurrences, sorted by the number of occurrences in a descending order. It is a requirement that I cannot control that this be returned as a 2-dimensional array of String.

So here is what I have so far:

static String[][] wordCountEngine(String document) {
    // your code goes here
    if (document == null || document.length() == 0)
        return null;

    Map<String, String> map = new HashMap<>();
    String[] allWords = document.toLowerCase().split("[^a-zA-Z]+");

    for (String s : allWords) {
        if (map.containsKey(s)) {

            int newVersion = (Integer.parseInt(map.get(s).substring(1, map.get(s).length())) + 1);
            String sb = Integer.toString(newVersion);
            map.put(s, sb);
        } else {
            map.put(s, "1");
        }
    }

    String[][] array = new String[map.size()][2];
    int count = 0;
    for (Map.Entry<String, String> entry : map.entrySet()) {
        array[count][0] = entry.getKey();
        array[count][1] = entry.getValue();
        count++;
    }

    return array;
}

I'm trying to use a HashMap to store the words and their occurrences. What is the best way to store key --> value pairs from a table into a String[][]. If the input is:

input:  document = "Practice makes perfect. you'll only
                get Perfect by practice. just practice!"

The output should be:

output: [ ["practice", "3"], ["perfect", "2"],
      ["by", "1"], ["get", "1"], ["just", "1"],
      ["makes", "1"], ["only", "1"], ["youll", "1"]  ]

How do I store data like this in a 2D array?

how to return multidimensional array from a function, can anyone tell how to return int type 2 dimensional array from a function which receives a two dimensional array as well as an argument I'm searching on net for some good stuff #include<string.h> int* getarray(int a[][2]); //taking a 2D array  This is because it shows the length of the string and before entering any string the length of the string is 0. Printing the array elements. The way a 2D character array is printed in not the same as a 2D integer array. This is because we see that all the spaces in the array are not occupied by the string entered by the user.

Just because you need to return a particular typed data-structure does not mean you need to create similarly typed map inside your method. Nothing prevents you from using Map<String, Integer> and then converting it to String[][]:

Here is the code that does not use Java8 streeams:

static String[][] wordCountEngine(String document) {
        // your code goes here
        if (document == null || document.length() == 0)
            return null;

        Map<String, Integer> map = new HashMap<>();

        for ( String s : document.toLowerCase().split("[^a-zA-Z]+") ){
            Integer c = map.get(s);
            map.put(s, c != null ? c + 1: 1);
        }

        String[][] result = new String[ map.size() ][ 2 ];

        int count = 0;
        for ( Map.Entry<String, Integer> e : map.entrySet() ){
            result[count][0] = e.getKey();
            result[count][1] = e.getValue().toString();
            count += 1;
        }

        return result;
    }  

And for fun a Java8 version:

static String[][] wordCountEngine(String document) {
    // your code goes here
    if (document == null || document.length() == 0)
        return null;

    return Arrays
    //convert words into map with word and count
    .stream( document.toLowerCase().split("[^a-zA-Z]+") )
    .collect( Collectors.groupingBy( s -> s, Collectors.summingInt(s -> 1) ) )
    //convert the above map to String[][]
    .entrySet()
    .stream().map( (e) -> new String[]{ e.getKey(), e.getValue().toString() } )
    .toArray( String[][]::new  );

}

How To Return 2D Array From Function In C & C++, You could create a structure and create a 2D array inside it, then pass a variable of that structure as an argument and return it. A C++ example How do I store a whole word into a single element in an array of strings in C? 15,275 Views. I do not fully understand how to return a 2D object. So I wrote a method that takes in an input with a document and I have to return a list of all unique words in it and their number of occurrences,

this is my Solution to Pramp's question although in C# I think it is the same Idea

   [TestMethod]
        public void PrampWordCountEngineTest()
        {

            string document = "Practice makes perfect. you'll only get Perfect by practice. just practice!";
            string[,] result = WordCountEngine(document);
            string[,] expected =
            {
                {"practice", "3"}, {"perfect", "2"},
                {"makes", "1"}, {"youll", "1"}, {"only", "1"},
                {"get", "1"}, {"by", "1"}, {"just", "1"}
            };
            CollectionAssert.AreEqual(expected,result);

        }
        public string[,] WordCountEngine(string document)
        {
            Dictionary<string, int> wordMap = new Dictionary<string, int>();
            string[] wordList = document.Split(' ');
            int largestCount = 0;
            foreach (string word in wordList)
            {
                string lowerWord = word.ToLower(); // can't assing to the same variable

                //remove special/punctuation characters
                var sb = new StringBuilder();
                foreach (var c in lowerWord)
                {
                    if (c >= 'a' && c <= 'z')
                    {
                        sb.Append(c);
                    }
                }
                string cleanWord = sb.ToString();
                if (cleanWord.Length < 1)
                {
                    continue;
                }
                int count = 0;
                if (wordMap.ContainsKey(cleanWord))
                {
                    count = wordMap[cleanWord];
                    count++;
                }
                else
                {
                    count = 1;
                }
                if (count > largestCount)
                {
                    largestCount = count;
                }
                wordMap[cleanWord] = count;
            }

            // we have a list of all of the words in the same length in a given cell of the big list
            List<List<string>> counterList = new List<List<string>>();
            for (int i = 0; i < largestCount + 1; i++)
            {
                counterList.Add(new List<string>());
            }
            foreach (var word in wordMap.Keys)
            {
                int counter = wordMap[word];
                counterList[counter].Add(word);
            }

            string[,] result = new string[wordMap.Keys.Count,2];
            int key = 0;
            //foreach list of words with the same length we insert the count of that word into the 2D array
            for (var index = counterList.Count-1; index > 0; index--)
            {
                var list = counterList[index];
                List<string> wordListCounter = list;
                if (wordListCounter == null)
                {
                    continue;
                }
                foreach (var word in wordListCounter)
                {
                    result[key, 0] = word;
                    result[key, 1] = index.ToString();
                    key++;
                }
            }
            return result;
        }

How to return a 2d array in C from a function, Using C++ powerful object oriented features, it is very easy to return a multi-​dimensional array. Just create a class How can I input string in 2D array in C​++?. This can be done by creating a two-dimensional array inside a function, allocating a memory and returning that array. The important thing is you need to FREE the matrix that was allocated. The source code of returning a two-dimensional array with reference to matrix addition is given here.

How to return multidimensional array using two parameters in C++ , In this post we will see how to pass two dimensional array and three dimensional array to a function in C++.We will also see how to return two  How to return an array in Java. In this section, we are going to learn how to return an array in Java. Remember: A method can return a reference to an array. The return type of a method must be declared as an array of the correct data type. Example 1. In the following example, the method returns an array of integer type.

Passing multidimensional array to a function returning , deepToString() method, which will return a String version of all elements of a 2D array, as shown in the following the example. import java.util.Arrays; /** * Java  If you want to combine all the String elements in the String array with some specific delimiter, then you can use convertStringArrayToString (String [] strArr, String delimiter) method that returns the String after combining them. Java Array to String Example

How to declare and Initialize two dimensional Array in Java with , This post is an extension of How to dynamically allocate a 2D array in C? int main(). {. int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};. print(arr);. return 0;. } Print all possible combinations of the string by replacing '$' with any other digit from the string  Hi everyone, Supposed I have a 2x2 matrix {dog, 0} {0, cat} I want to return "cat" by searching for "ca" which is in cell C3. I can get the following formula to work on a 1d array, but not sure what my approach should be when i make it 2d.

Comments
  • That's a terrible idea, as you're using Strings to represent numeric data. Why not simply return a Map<String, Integer> or create a custom type that holds String and int values?
  • @HovercraftFullOfEels Yeah, I think your right. I'm better off creating my own Data type to store the values in. This was a coding challenge, so I had to return a String[][]. Not my choice. Thanks anyways.
  • Hmph, well, I don't approve of their requirements.
  • "This was a coding challenge, so I had to return a String[][]. Not my choice." Coding Challenges are not the best way to learn Java. You better go your way through the official tutorial first: docs.oracle.com/javase/tutorial
  • @TimothyTruckle Thanks, I'll keep that in mind.
  • Overuse of Strings to represent non-text data is a design smell. This is the appropriate solution.
  • This was a coding challenge and they wanted a String[][] as a return value. But thanks anyways.
  • @RockySingh I added a note regarding that situation.
  • @luk2302 Thanks.