Different Ways to Generate String by using Characters and Numbers in Java
Given a number num and String str, the task is to generate the new String by extracting the character from the string by using the index value of numbers.
Examples:
Input: str = “GeeksforGeeks”
num = 858
Output: GfG
Explanation: The 8th, 5th, and 8th position of the characters are extracting from the given string and generate a new string.
Input: str = “Java”
num = 12
Output: The 1st and 2nd position of the characters are extracting from the given string and generate a new string.
Method 1: Using Two Traversals
- Get the string and number to generate a new string.
- Initialize a variable that stores the final answer.
- Converting the given number into the string.
- Traverse the loop from start to end.
- Getting the last digit of the number and add kth position character into the variable answer.
- Traverse the loop in the reverse order and adding the jth position character into the variable finalAnswer.
- Now, print the result.
Java
class GFG {
public static String generateNewString(String str,
int num)
{
String finalAnswer = "" ;
String answer = "" ;
String index = String.valueOf(num);
for ( int i = 0 ; i < index.length(); i++) {
int k = num % 10 ;
answer = answer + str.charAt(k);
num = num / 10 ;
}
for ( int j = answer.length() - 1 ; j >= 0 ; j--) {
finalAnswer = finalAnswer + answer.charAt(j);
}
return finalAnswer;
}
public static void main(String args[])
{
String str = "GeeksforGeeks" ;
int num = 858 ;
System.out.println(generateNewString(str, num));
}
}
|
Method 2: Using One Traversal
- Get the string and number to generate a new string.
- Initialize a variable that stores the result.
- Converting the given number into the string.
- Traverse the loop from start to end.
- Get the right index and adding kth position character into the result.
- Now, print the result.
Java
class GFG {
public static String generateNewString(String str,
int num)
{
String result = "" ;
String index = String.valueOf(num);
for ( int i = 0 ; i < index.length(); i++) {
int k = index.charAt(i) - 48 ;
result = result + str.charAt(k);
}
return result;
}
public static void main(String args[])
{
String str = "GeeksforGeeks" ;
int num = 858 ;
System.out.println(generateNewString(str, num));
}
}
|
Time Complexity: O(N)
Last Updated :
05 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...