Example 1:
Input: str ="Hello World" Output: char[] =[H, e, l, l, o, , W, o, r, l, d]
Approach 1
Java
import java.util.Arrays;
public class StrToCharArray {
public static void main(String[] args) {
String str = "Hello World";
Character[] ch = strToChar(str);
System.out.println(Arrays.asList(ch));
}
// convert string to char[]
private static Character[] strToChar(String str) {
Character arr[] = new Character[str.length()];
for (int i = 0; i < arr.length; i++) {
arr[i] = str.charAt(i);
}
return arr;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to convert from
//string to character array
vector<char> stringCharArray(string str)
{
vector<char> ch;
for(int i=0;i<str.size();i++)
ch.push_back(str[i]);
return ch;
}
int main()
{
string str="Hello World";
vector<char> ch=stringCharArray(str);
cout<<"[";
for(int i=0;i<ch.size();i++)
{
if(i!=ch.size()-1)
cout<<ch[i]<<", ";
else
cout<<ch[i];
}
cout<<"]";
return 0;
}
Approach 2
Java
public class StrToCharArray {
public static void main(String[] args) {
String str = "Hello World";
char[] st = str.toCharArray();
printCharArray(st);
}
private static void printCharArray(char[] st) {
for (int i = 0; i < st.length; i++) {
System.out.print(st[i] + " ");
}
System.out.println();
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to convert from
//string to character array
void stringCharArray(string str)
{
char ch[str.size()];
strcpy(ch,str.c_str());
cout<<"[";
for(int i=0;i<str.size();i++)
{
if(i!=str.size()-1)
cout<<ch[i]<<", ";
else
cout<<ch[i];
}
cout<<"]";
}
int main()
{
string str="Hello World";
stringCharArray(str);
return 0;
}
No comments:
Post a Comment