java实现strncmp函数功能(附完整源码)
时间: 2023-12-21 14:20:53 浏览: 42
好的,以下是Java实现strncmp函数功能的完整源码:
```java
public class Strncmp {
public static int strncmp(String str1, String str2, int n) {
// 获取字符串长度
int len1 = str1.length();
int len2 = str2.length();
// 取两个字符串中较小的长度
int minLen = Math.min(len1, Math.min(len2, n));
// 逐个字符进行比较
for (int i = 0; i < minLen; i++) {
char c1 = str1.charAt(i);
char c2 = str2.charAt(i);
if (c1 != c2) {
// 如果不相等,返回它们的 ASCII 码差值
return (int) c1 - (int) c2;
}
}
// 如果前 minLen 个字符都相同,则返回它们的长度差值
return len1 - len2;
}
public static void main(String[] args) {
String str1 = "hello world";
String str2 = "hello";
int n = 5;
int result = strncmp(str1, str2, n);
System.out.println("strncmp result: " + result);
}
}
```
你可以将上述代码保存为 Strncmp.java 文件,并使用 JDK 中的编译器编译运行。当你运行此程序时,你将会看到输出的 strncmp 的结果为 6。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)