原文:
给定字符串 str,任务是打印字符串的中间字符。如果字符串的长度是偶数,那么会有两个中间字符,我们需要打印第二个中间字符。
示例:
输入: str = "java" 输出: v 解释: 给定字符串的长度是偶数。 因此,会有两个中间字符‘a’和‘v’,我们打印第二个中间字符。
输入: str = "geeksforgeeks" 输出: o 解释: 给定字符串的长度是奇数。 因此,只有一个中间字符,我们打印该中间字符。
进场:
- 获取要找到中间字符的字符串。
- 计算给定字符串的长度。
- 查找字符串的中间索引。
- 现在,使用 java 中的函数
下面是上述方法的实现:
c
// c program to implement
// the above approach
#include
using namespace std;
// function that prints the middle
// character of a string
void printmiddlecharacter(string str)
{
// finding string length
int len = str.size();
// finding middle index of string
int middle = len / 2;
// print the middle character
// of the string
cout << str[middle];
}
// driver code
int main()
{
// given string str
string str = "geeksforgeeks";
// function call
printmiddlecharacter(str);
return 0;
}
// this code is contributed by sapnasingh
java 语言(一种计算机语言,尤用于创建网站)
// java program for the above approach
class gfg {
// function that prints the middle
// character of a string
public static void
printmiddlecharacter(string str)
{
// finding string length
int len = str.length();
// finding middle index of string
int middle = len / 2;
// print the middle character
// of the string
system.out.println(str.charat(middle));
}
// driver code
public static void
main(string args[])
{
// given string str
string str = "geeksforgeeks";
// function call
printmiddlecharacter(str);
}
}
python 3
# python3 program for the above approach
# function that prints the middle
# character of a string
def printmiddlecharacter(str):
# finding string length
length = len(str);
# finding middle index of string
middle = length // 2;
# print the middle character
# of the string
print(str[middle]);
# driver code
# given string str
str = "geeksforgeeks";
# function call
printmiddlecharacter(str);
# this code is contributed by sapnasingh4991
c
// c# program for the above approach
using system;
class gfg{
// function that prints the middle
// character of a string
public static void printmiddlechar(string str)
{
// finding string length
int len = str.length;
// finding middle index of string
int middle = len / 2;
// print the middle character
// of the string
console.writeline(str[middle]);
}
// driver code
public static void main(string []args)
{
// given string str
string str = "geeksforgeeks";
// function call
printmiddlechar(str);
}
}
// this code is contributed by amal kumar choubey
java 描述语言
output:
o
时间复杂度: o(1) 辅助空间: o(1)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处