📜  打印字符串的中间字符

📅  最后修改于: 2021-09-02 06:38:06             🧑  作者: Mango

给定字符串str ,任务是打印字符串的中间字符。如果字符串的长度是偶数,那么中间会有两个字符,我们需要打印第二个中间字符。

例子:

方法:

  1. 获取要找到中间字符的字符串。
  2. 计算给定字符串的长度。
  3. 查找字符串的中间索引。
  4. 现在,在Java使用函数charAt() 在索引中间打印字符串的中间字符。

下面是上述方法的实现:

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);
    }
}


Python3
# 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;
 
    # Prthe 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


输出:
o



时间复杂度: O(1)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live