C或C ++。如何比较两个字符串给char *指针? [英] C or C++. How to compare two strings given char * pointers?

查看:360
本文介绍了C或C ++。如何比较两个字符串给char *指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在排序我的汽车数组两种方式。一年一年,如下所示。和另一个通过make。 Make是一个char *当我只有指针时,如何比较字符串?

  int i,j; 
for(i = 0; i <100; i ++){
for(j = 0; j< 100-i; j ++){
if(carArray [i]!= NULL& ; and carArray [j]!= NULL&& carArray [j + 1]!= NULL){
if(carArray [i] - > year> carArray [j + 1]年){
swap(carArray [j],carArray [j + 1]);
}
}
}
}

上面的方法适用于int's(year)。

解决方案

几乎任何一种,方式是调用 strcmp 。如果您的字符串(由于某些奇怪的原因)不是NUL终止,您应该使用



但是,在C ++中,你真的不应该操作char数组中的字符串,如果你可以合理地避免它。请改用 std :: string 。 p>

I am sorting my array of car two ways. one by year which is shown below. and another one by make. Make is a char* How do I compare strings when I just have pointers to them?

int i, j;
for(i=0; i<100; i++){
    for(j=0; j<100-i; j++){
        if(carArray[i]!=NULL && carArray[j]!= NULL && carArray[j+1]!=NULL){
            if(carArray[i]->year > carArray[j+1]->year){
                swap(carArray[j], carArray[j+1]);
            }
        }
    }
}

The above method works for int's (year). How can I make it work for char pointers?

解决方案

In pretty much either one, the way is to call strcmp. If your strings (for some weird reason) aren't NUL terminated, you should use strncmp instead.

However, in C++ you really shouldn't be manipulating strings in char arrays if you can reasonably avoid it. Use std::string instead.

这篇关于C或C ++。如何比较两个字符串给char *指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆