多个字符串中的第一个和最后一个char

时间:2014-06-25 23:40:06

标签: c++ c

拜托,我需要帮助!我需要比较多个字符串中的第一个和最后一个字符。  我不知道该怎么做。  字符串是随机生成的。

例如:用户类型不同的字符串然后程序需要比较每个字符串的第一个和最后一个字符串 。例如:3个字符串。 “钱”“爸爸”“生成”。

...目标是我在“爸爸”和“生成”中获得正值,因为第一个字符串和字符串“爸爸”和“生成”的最后字符是相同的。我是先生。请帮忙。

这是我卡住的代码。惹坏英语。 :(

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>

char funkcija() {
    FILE *c;
    c = fopen("datoteka.txt", "r");
    if (c == NULL) {
        printf("Error in opening!");
        getch();
        exit(1);
    }

    int i = 0;
    char polje[100];
    while (fscanf(c, "%s", polje) == 1) {
        int duljina = strlen(polje);
        if (polje[0] == polje[duljina - 1]) {
            i++;
        }
    }

    printf("Rezultat je: %d", i);
}

int main() {

    funkcija();
    getch();
    return 0;
}

first of all i thank you all for help. I am rly sorry if i asked wrong question or if it wasnt      clear enough. I will try put the part of the code that botthers me most.

if(array[0]==array[length-1]){
                   i++;
                   }  

here`once again i am rly sorry for bad explanation of problem :/

2 个答案:

答案 0 :(得分:3)

1)使用std::string

2)将逻辑放在函数

3)检查空字符串

#include <iostream>
using namespace std;

bool HasFirstAndLastCharEqual(const std::string& s)
{
    if(s.empty())
        return false;
    return  s.front() == s.back();
}

int main() {
    cout << HasFirstAndLastCharEqual("money") << endl;
    cout << HasFirstAndLastCharEqual("dad") << endl;
    cout << HasFirstAndLastCharEqual("generating") << endl;
}

答案 1 :(得分:0)

更改这些行

   int duljina=strlen(polje);      
   if(strcmp(polje[0])==strcmp(polje[duljina-1])){    
                   i++;
                   }  

以下方式

   size_t duljina=strlen(polje);      
   if ( polje[0] && polje[0] == polje[duljina-1] ){    
                   i++;
                   }  

如果您需要C ++代码,那么它可以采用以下方式(无需测试)

#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

int main() 
{
    std::ifstream in( "datoteka.txt" );

    size_t n = std::count_if( std::istream_iterator<std::string>( in ),
                              std::istream_iterator<std::string>(),
                              []( const std::string &s )
                              {
                                return s[0] && s.front() == s.back();
                              } );

    std::cout << n << std::endl;

    return 0;
}