-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringManipulation.java
More file actions
55 lines (51 loc) · 1.96 KB
/
StringManipulation.java
File metadata and controls
55 lines (51 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.Scanner;
public class StringManipulation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first string:");
String input1 = scanner.nextLine();
char[] string1 = input1.toCharArray();
// a) string length
int length1 = stringLength(string1);
System.out.println("Length of the first string:" + length1);
// b) finding a character at a particular position
System.out.println("Enter the position to find the character:");
int position = scanner.nextInt();
scanner.nextLine();
if (position > 0 && position < length1) {
char character = charAt(string1, position - 1);
System.out.println("Character at position " + (position) + ":" + character);
} else {
System.out.println("Position out of bounds.");
}
System.out.println("Enter the second string:");
String input2 = scanner.nextLine();
char[] string2 = input2.toCharArray();
// c) concatenating two strings
char[] concatenatedString = concatenate(string1, string2);
System.out.println("Concatenated String:" + new String(concatenatedString));
scanner.close();
}
public static int stringLength(char[] string) {
int length = 0;
for (char c : string) {
length++;
}
return length;
}
public static char charAt(char[] string, int position) {
return string[position];
}
public static char[] concatenate(char[] string1, char[] string2) {
int length1 = stringLength(string1);
int length2 = stringLength(string2);
char[] result = new char[length1 + length2];
for (int i = 0; i < length1; i++) {
result[i] = string1[i];
}
for (int i = 0; i < length2; i++) {
result[length1 + i] = string2[i];
}
return result;
}
}