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

132 阅读2分钟

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

改进文章

保存文章

喜欢的文章

  • 最后更新: 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 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] <<" ";
}
}

爪哇

// Java Program to retuen indices of a given string
// from the multidimensional string array
public class Main {
// method to return an array of indices of keyString
public static int[] findIndex(String stringArr[][],
String keyString)
{
// intialising result array to -1 in case keyString
// is not found
int result[] = { -1, -1 };
// iteration over all the elements of the 2-D array
// rows
for (int i =0; i < stringArr.length; i++) {
// columns
for (int j =0; j < stringArr[i].length; j++) {
// if keyString is found
if (stringArr[i][j].equals(keyString)) {
result[0] = i;
result[1] = j;
return result;
}
}
}
// if keyString is not found then -1 is returned
return result;
}
// Driver Code
public static void main(String args[])
{
// given string array
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
int[] result = findIndex(stringArr, keyString);
// printing the indices returned
System.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

保存