shell脚本判断是否是回文序列
时间: 2023-11-25 18:51:51 浏览: 46
以下是一个shell脚本判断是否是回文序列的例子:
```shell
#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: $0 filename string_length"
exit -1
fi
filename=$1
basepattern='/^\(.\)'
count=$(( $2/2 ))
# matche certain length
for ((i=1; i < $count; i++))
do
basepattern=$basepattern'\(.\)';
done
# the length is even
if [ $(( $2 % 2)) -ne 0 ]
then
basepattern=$basepattern'.';
fi
for ((count; count > 0; count--))
do
basepattern=$basepattern'\'"$count";
done
basepattern=$basepattern'$/p'
sed -n "$basepattern" $filename
```
该脚本的原理是:将输入的字符串分成两半,然后将其中一半反转,最后比较两半是否相等。如果相等,则说明该字符串是回文序列。
相关问题
shell脚本回文序列
以下是一个判断字符串是否为回文序列的Shell脚本例子:
```shell
#!/bin/bash
echo "请输入一个字符串:"
read str
len=${#str}
mid=$(($len/2))
for (( i=0; i<$mid; i++ )); do
if [ "${str:$i:1}" != "${str: -$(($i+1)):1}" ]; then
echo "$str 不是回文序列"
exit
fi
done
echo "$str 是回文序列"
```
该脚本首先提示用户输入一个字符串,然后计算字符串长度并求出中间位置。接着使用for循环遍历前半部分字符,判断其是否与后半部分对应位置的字符相同,如果不同则输出不是回文序列并退出程序,否则输出是回文序列。
c++用指针数组输入并判断字符串是否是回文序列
可以按照以下步骤来实现:
1. 定义一个指针数组,存储字符串。
2. 从控制台输入字符串,使用 `gets()` 或 `fgets()` 函数,将输入的字符串存储到指针数组中。
3. 定义两个指针,分别指向字符串的头和尾。
4. 使用 `while` 循环,比较两个指针所指向的字符是否相等,如果相等,则将两个指针向中间移动,继续比较下一个字符,直到两个指针相遇或者交错。
5. 如果两个指针相遇或者交错,则说明该字符串是回文序列。
完整的代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int MAX_SIZE = 100;
char* str[MAX_SIZE]; // 定义指针数组
char buf[MAX_SIZE];
cout << "请输入一个字符串: ";
gets(buf); // 从控制台输入字符串
// 将字符串存储到指针数组中
int len = strlen(buf);
for (int i = 0; i < len; i++)
{
str[i] = &buf[i];
}
// 判断字符串是否是回文序列
char* left = str[0];
char* right = str[len - 1];
while (left < right)
{
if (*left != *right)
{
cout << "不是回文序列" << endl;
return 0;
}
left++;
right--;
}
cout << "是回文序列" << endl;
return 0;
}
```