Accessing characters by index in a string.
To access any character in a String, we need:
- A non-empty string (say “str”)
- A position/index of the character from where it is to be accessed. (say “k”)
Using these two, the character can be easily accessed using the below syntax:
char ch = str[k];
OR
char ch = str.charAt(k);
Below is the implementation of the above approach:
// CPP code for accessing an element by index
#include <iostream>
#include <string>
using namespace std;
// Function to demonstrate insert
char accessCharByIndex(string str, int k)
{
// return the character at Kth index
// in the string str
return str[k];
}
// Driver code
int main()
{
string str("w3wiki ");
int k = 4;
cout << accessCharByIndex(str, k) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
// Function to demonstrate accessing character by index
char accessCharByIndex(char* str, int k)
{
// Return the character at the kth index in the string
return str[k];
}
// Driver code
int main()
{
char str[] = "w3wiki ";
int k = 4;
printf("%c\n", accessCharByIndex(str, k));
return 0;
}
public class GFG {
// Function to demonstrate accessCharByIndex
public static char accessCharByIndex(String str, int k) {
// Return the character at the k-th index in the string str
return str.charAt(k);
}
// Driver code
public static void main(String[] args) {
String str = "w3wiki ";
int k = 4;
System.out.println(accessCharByIndex(str, k));
}
}
# Function to access an element by index
def access_char_by_index(s, k):
# Return the character at the kth index in the string s
return s[k]
# Driver code
def main():
string_value = "w3wiki "
index = 4
print(access_char_by_index(string_value, index))
# Run the main function
if __name__ == "__main__":
main()
using System;
class Program {
// Function to access a character by index
static char AccessCharByIndex(string str, int k)
{
// Return the character at the k-th index
return str[k];
}
static void Main()
{
string str = "w3wiki ";
int k = 4;
Console.WriteLine(AccessCharByIndex(str, k));
}
}
// Function to demonstrate access by index
function accessCharByIndex(str, k) {
// Return the character at the kth index in the string str
return str[k];
}
// Driver code
let str = "w3wiki ";
let k = 4;
console.log(accessCharByIndex(str, k));
Output
s
Basic String Operations with Implementation
In this post, we will look into some of the basic String operations such as:
- Accessing characters by index in a string.
- Inserting character into a String.
- Modifying character in String
- Deletion of Character in String
- Concatenating strings (combining multiple strings into one).
- Finding the length of a string
- Comparing strings for equality or lexicographical order
Let us consider the basic String operations one by one.