查找并返回多维数组中给定字符串的索引
改进文章
保存文章
喜欢的文章
- 最后更新: 2022年6月3日
给定一个由字符串组成的多维数组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 retuen indices of a given// string from the multidimensional array#include <bits/stdc++.h>using namespace std;// Method to return an array of indices// of keyStringvector<int> findIndex(vector<vector<string> > stringArr,string keyString){// Intialising result array to -1// in case keyString is not foundvector<int> result{ -1, -1 };// Iteration over all the elements// of the 2-D array// Rowsfor (int i = 0; i < stringArr.size(); i++) {// Columnsfor (int j = 0; j < stringArr[i].size(); j++) {// If keyString is foundif (stringArr[i][j] == keyString) {result[0] = i;result[1] = j;return result;}}}// If keyString is not found// then -1 is returnedreturn result;}// Driver Codeint main(){// Given string arrayvector<vector<string> > stringArr{ {"a","h","b" },{"c","d","e" },{"g","t","r" } };// Given key String to be foundstring keyString ="e";// Calling the method which// returns an array of indicesvector<int> result = findIndex(stringArr, keyString);// Printing the indices returnedcout <<"The indices are: ";for (int i = 0; i < result.size(); i++) {cout << result[i] <<" ";}} |
爪哇
// Java Program to retuen indices of a given string// from the multidimensional string arraypublic class Main {// method to return an array of indices of keyStringpublic static int[] findIndex(String stringArr[][],String keyString){// intialising result array to -1 in case keyString// is not foundint result[] = { -1, -1 };// iteration over all the elements of the 2-D array// rowsfor (int i =0; i < stringArr.length; i++) {// columnsfor (int j =0; j < stringArr[i].length; j++) {// if keyString is foundif (stringArr[i][j].equals(keyString)) {result[0] = i;result[1] = j;return result;}}}// if keyString is not found then -1 is returnedreturn result;}// Driver Codepublic static void main(String args[]){// given string arrayString[][] stringArr = { {"a","h","b" },{"c","d","e" },{"g","t","r" } };// given key String to be foundString keyString ="e";// calling the method which returns an array of// indicesint[] result = findIndex(stringArr, keyString);// printing the indices returnedSystem.out.print("The indices are:- ");for (int i =0; i < result.length; i++) {System.out.print(result[i] +" ");}}} |
输出
The indices are: 1 2
我的个人笔记arrow_drop_up
保存