接着上面的提问,为什么由于每个字符串数组都没有以 '\0' 结尾
时间: 2024-03-10 17:51:16 浏览: 27
在 C/C++ 中,字符串的结尾必须以 `'\0'` 字符作为标志,表示字符串的结束。这个字符在字符串的最后一个字节处,因此被称为字符串的“空字符”或“结束符”。
在这段代码中,每个字符串数组并没有以 `'\0'` 结尾,因此不能使用 `*(p+j)!="\0"` 的方式来判断循环的终止条件。实际上,这种循环方式可能会导致访问到内存中未定义的区域,从而出现未知错误。
如果想要在循环中遍历每个字符串数组中的所有元素,可以将每个字符串数组的长度保存在另外一个数组中,并在循环中使用该长度来作为判断循环终止的条件。例如,可以使用 `strlen` 函数来获取每个字符串的长度,然后在循环中判断当前元素是否到达字符串的结尾,例如:
```
char* arr[][3]={{"北京","沈阳","哈尔滨"},{"北京","张家口"},{"北京","石家庄","武汉"}};
int len[3]={3,2,3};
for(int i=0; i<3; i++){
char** p = arr[i];
for(int j=0; j<len[i]; j++){
if(*(*(p+j)) != '\0'){
cout << *(p+j) << endl;
}
}
}
```
这样就可以安全地循环遍历每个字符串数组中的所有元素了。
相关问题
用python实现去掉字符串数组中每个字符串的空格
可以使用以下代码来实现去掉字符串数组中每个字符串的空格:
```python
def remove_spaces(strings):
new_strings = []
for string in strings:
new_string = string.replace(" ", "")
new_strings.append(new_string)
return new_strings
# 示例用法
strings = ["hello world", " python ", " coding "]
new_strings = remove_spaces(strings)
print(new_strings)
```
在上述代码中,我们定义了一个名为 `remove_spaces` 的函数,它接受一个字符串数组作为参数。在函数内部,我们创建了一个新的空数组 `new_strings`,用于存储去掉空格后的每个字符串。然后,我们使用 `replace()` 方法将每个字符串中的空格替换为空字符,并将替换后的字符串添加到新数组 `new_strings` 中。最后,我们返回新数组。
在示例用法部分,我们定义了一个字符串数组 `strings`,其中包含了一些带有空格的字符串。然后,我们调用 `remove_spaces` 函数,并将返回的新数组存储在 `new_strings` 变量中。最后,我们输出 `new_strings` 的内容,即去掉空格后的字符串数组。
请注意,上述代码中使用了 `replace()` 方法来去掉空格。如果你想只去掉字符串开头和结尾的空格,可以使用 `strip()` 方法。
python判断数组中每个字符串结尾
要判断数组中每个字符串结尾,可以使用Python中的字符串方法`endswith()`。该方法接受一个字符串作为参数,判断当前字符串是否以该参数指定的字符串结尾。可以遍历数组中的每个字符串,然后依次调用`endswith()`方法进行判断。以下是示例代码:
```python
arr = ['hello world', 'python', 'apple', 'banana']
suffix = 'ld'
for s in arr:
if s.endswith(suffix):
print(s + ' ends with ' + suffix)
else:
print(s + ' does not end with ' + suffix)
```
输出结果为:
```
hello world ends with ld
python does not end with ld
apple does not end with ld
banana ends with ld
```