查找并返回多维数组中给定字符串的索引的方法

340 阅读1分钟

查找并返回多维数组中给定字符串的索引

给定一个由字符串组成的多维数组stringArr和一个需要查找的关键字符串,任务是返回该关键字符串在数组中的坐标/索引

例子。

输入: stringArr[][] = { { "a", "h", "b"}, {"c", "d", "e"}, {"g", "t", "r"}.}, keyString = "e**"**
输出= {1, 2}
解释。 按照基于0的 索引 ,keyString存在于多维数组中的(1, 2)。

办法。按 照步骤找到一个字符串在多维数组中的坐标/索引。

  • 首先,遍历数组中的所有元素,检查第一行的每个元素,然后是第二行,以此类推。
  • 然后如果在数组中找到keyString,就简单地返回索引
  • 否则就返回**-1**作为索引。

下面是上述方法的实现。

C++

// CPP Program to return indices of a given
// string from the multidimensional array
#include <bits/stdc++.h>
using namespace std;

// Method to return an array of indices
// of keyString
vector<int> findIndex(vector<vector<string> > stringArr,
					string keyString)
{

	// Intialising result array to -1
	// in case keyString is not found
	vector<int> result{ -1, -1 };

	// Iteration over all the elements
	// of the 2-D array

	// Rows
	for (int i = 0; i < stringArr.size(); i++) {

		// Columns
		for (int j = 0; j < stringArr[i].size(); j++) {

			// If keyString is found
			if (stringArr[i][j] == keyString) {
				result[0] = i;
				result[1] = j;
				return result;
			}
		}
	}

	// If keyString is not found
	// then -1 is returned
	return result;
}

// Driver Code
int main()
{

	// Given string array
	vector<vector<string> > stringArr{ { "a", "h", "b" },
									{ "c", "d", "e" },
									{ "g", "t", "r" } };

	// Given key String to be found
	string keyString = "e";

	// Calling the method which
	// returns an array of indices
	vector<int> result = findIndex(stringArr, keyString);

	// Printing the indices returned
	cout << "The indices are: ";
	for (int i = 0; i < result.size(); i++) {
		cout << result[i] << " ";
	}
}

输出

The indices are: 1 2