C++与java中的字符串相等
2021/8/11 20:07:00
本文主要是介绍C++与java中的字符串相等,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
C++中的字符串相等
string:
1.通过==
C++中的string类对操作符==实现了重载,可用来判断两字符串的内容是否相等
2.通过std::string::compare
定义:
int compare (const string& comparing_str) const;
value | relation between compared string and comparing string |
---|---|
0 | They compare equal |
>0 | Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer. |
<0 | Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter. |
原生字符串char*
①先通过string::c_str()转换为原生c的字符串:
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
②后通过strcmp()比较两个字符串
int strcmp ( const char * str1, const char * str2 );
value | indicates |
---|---|
<0 | the first character that does not match has a lower value in ptr1 than in ptr2 |
0 | the contents of both strings are equal |
>0 | the first character that does not match has a greater value in ptr1 than in ptr |
实验
源码:
#include<iostream> #include<vector> #include<string> using namespace std; int main() { string s1="abc123"; string s2="abc123"; cout<<&s1<<endl; cout<<&s2<<endl; cout<<(s1==s2)<<endl; cout<<s1.compare(s2)<<endl; return 0; }
输出:
Java中的字符串相等:
String:
1.==
比较的是两个String对象指向的地址值
2.equals()
String类重写了euqals()方法,比较的是字符串的内容
实验
源码:
public class StringTes { public static void main(String[] args) { String a=new String("abc123"); String b=new String("abc123"); String c="xyz"; String d="xyz"; String s1="xy"; String s2="z"; String s3=s1+s2; System.out.println("hash codes of a and b:"); System.out.println(System.identityHashCode(a)); System.out.println(System.identityHashCode(b)); System.out.println("a==b:"); System.out.println(a==b); System.out.println("hash codes of c and d:"); System.out.println(System.identityHashCode(c)); System.out.println(System.identityHashCode(d)); System.out.println("hash code of s3:"); System.out.println(System.identityHashCode(s3)); System.out.println("c==d:"); System.out.println(c==d); } }
输出:
这篇关于C++与java中的字符串相等的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-102025 蛇年,J 人直播带货内容审核团队必备的办公软件有哪 6 款?
- 2025-01-10高效运营背后的支柱:文档管理优化指南
- 2025-01-10年末压力山大?试试优化你的文档管理
- 2025-01-10跨部门协作中的进度追踪重要性解析
- 2025-01-10总结 JavaScript 中的变体函数调用方式
- 2025-01-10HR团队如何通过数据驱动提升管理效率?6个策略
- 2025-01-10WBS实战指南:如何一步步构建高效项目管理框架?
- 2025-01-10实现精准执行:团队协作新方法
- 2025-01-10如何使用工具提升活动策划团队的工作效率?几个必备工具推荐
- 2025-01-10WiX 标签使用介绍:打造专业安装程序的利器