字符串与 c++ 的比较

Comparisons of strings with c++

本文关键字:比较 c++ 字符串      更新时间:2023-10-16

我曾经在C++中有一些代码,它将字符串存储为字符矩阵中的一系列字符(字符串是一行)。类 Character matrix 和 LogicalVector 由 Rcpp.h 提供:

LogicalVector unq_mat( CharacterMatrix x ){
  int nc = x.ncol() ; // Get the number of columns in the matrix. 
  LogicalVector out(nc); // Make a logical (bool) vector of the same length.
  // For every col in the matrix, assess whether the column contains more than one unique character.
  for( int i=0; i < nc; i++ ) {
    out[i] = unique( x(_,i) ).size() != 1 ;
    }
  return out;
}

逻辑向量标识哪些列包含多个唯一字符。然后将其传递回 R 语言并用于操作矩阵。这是一种非常R的思维方式。然而,我有兴趣在C++中发展我的思维,我想写一些实现上述目标的东西: 所以找出n个字符串中的哪些字符并不完全相同,但最好使用stl类,如std::string。作为概念示例,给定三个字符串:A = "Hello", B = "Heleo", C = "Hidey"。代码会指出位置/字符 2,3,4,5 不是一个值,但位置/字符 1("H")在所有字符串中都是相同的(即只有一个唯一值)。我在下面有一些我认为有效的内容:

std::vector<int> StringsCompare(std::vector<string>& stringVector) {
    std::vector<int> informative;
    for (int i = 0; i < stringVector[0].size()-1; i++) {
        for (int n = 1; n < stringVector.size()-1; n++) {
            if (stringVector[n][i] != stringVector[n-1][i]) {
                informative.push_back(i);
                break;
            }
        }
    }
    return informative;
}

它应该使用外部循环和内部循环遍历每个字符位置(0 到 string-1 的大小),查看字符串 n 中的字符是否与字符串 n-1 中的字符不同。在字符都相同的情况下,例如我上面的 hello 示例中的 H,这永远不会是真的。对于字符串中的字符不同的情况,将满足 inter 循环 if 语句,记录字符位置,并断开内部循环。然后,我得到一个向量,其中包含 n 个字符串中字符的指示,其中字符并不完全相同。但是,这两个函数给了我不同的答案。我还能如何逐个字符遍历 n 个字符串并检查它们是否都相同?

谢谢本。

我希望@doctorlove能提供一个答案。 我会在这里输入一个,以防他不这样做。

要按索引循环访问字符串或向量的所有元素,您需要从 0 isize()-1for (int i=0; i<str.size(); i++)停在尺寸的短处,即停在size()-1 . 因此,请删除 -1。

其次,C++数组是从 0 开始的,因此您必须进行调整(通过将 1 加到推送到向量中的值)。

std::vector<int> StringsCompare(std::vector<std::string>& stringVector) {
    std::vector<int> informative;
    for (int i = 0; i < stringVector[0].size(); i++) {
        for (int n = 1; n < stringVector.size(); n++) {
            if (stringVector[n][i] != stringVector[n-1][i]) {
                informative.push_back(i+1);
                break;
            }
        }
    }
    return informative;
}

关于此代码需要注意的几点:

  1. 该函数应采用对向量的常量引用,因为输入向量不会被修改。 这里不是真正的问题,但由于各种原因,将未修改的输入引用声明为 const 是个好主意。
  2. 这假定所有字符串至少与第一个字符串一样长。 如果这不成立,则代码的行为是未定义的。 对于"生产"代码,您应该在提取每个字符串的第i个元素之前检查长度。