给定一个字符串,任务是使用命令行参数检查此字符串是否为回文。
例子:
Input: str = "Geeks"
Output: No
Input: str = "GFG"
Output: Yes
方法:
- 由于该字符串是作为命令行参数输入的,因此不需要专用的输入行
- 从命令行参数中提取输入字符串
- 使用循环逐个字符遍历此String字符,直到字符串长度的一半
- 检查字符从一端配以从另一端的字符
- 如果任何字符不匹配,则字符串不是回文
- 如果所有字符匹配,则字符串为回文
程序:
C
// C program to check if a string is Palindrome
// using command line arguments
#include
#include
#include
// Function to reverse a string
int isPalindrome(char* str)
{
int n = strlen(str);
int i;
// Check if the characters from one end
// match with the characters
// from the other end
for (i = 0; i < n / 2; i++)
if (str[i] != str[n - i - 1])
// Since characters do not match
// return 0 which resembles false
return 0;
// Since all characters match
// return 1 which resembles true
return 1;
}
// Driver code
int main(int argc, char* argv[])
{
int res = 0;
// Check if the length of args array is 1
if (argc == 1)
printf("No command line arguments found.\n");
else {
// Get the command line argument
// and check if it is Palindrome
res = isPalindrome(argv[1]);
// Check if res is 0 or 1
if (res == 0)
// Print No
printf("No\n");
else
// Print Yes
printf("Yes\n");
}
return 0;
}
Java
// Java program to check if a string is Palindrome
// using command line arguments
class GFG {
// Function to reverse a string
public static int isPalindrome(String str)
{
int n = str.length();
// Check if the characters from one end
// match with the characters
// from the other end
for (int i = 0; i < n / 2; i++)
if (str.charAt(i) != str.charAt(n - i - 1))
// Since characters do not match
// return 0 which resembles false
return 0;
// Since all characters match
// return 1 which resembles true
return 1;
}
// Driver code
public static void main(String[] args)
{
// Check if length of args array is
// greater than 0
if (args.length > 0) {
// Get the command line argument
// and check if it is Palindrome
int res = isPalindrome(args[0]);
// Check if res is 0 or 1
if (res == 0)
// Print No
System.out.println("No\n");
else
// Print Yes
System.out.println("Yes\n");
}
else
System.out.println("No command line "
+ "arguments found.");
}
}
输出:
- 在C中:
- 在Java:
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。