开发者

Add a String to an Array

开发者 https://www.devze.com 2023-02-22 05:10 出处:网络
How can I create a 开发者_JAVA百科string array in the C language?Its length should be five, and a loop should be used to get input from the user to fill the array with.Finally, I should print all stri

How can I create a 开发者_JAVA百科string array in the C language? Its length should be five, and a loop should be used to get input from the user to fill the array with. Finally, I should print all string values in the array to the user.


A string in C is really an array of characters. If you want to make a character array of length 256, you can do it like this:

char my_var[256];

You can read in a string of length 128 from standard input like this:

#include <stdio.h>
// ...
fgets(my_var,128,stdin);

You can print out a string like this:

printf("String is: %s",my_var);

A string is stored in the array character-by-character, and ends with the null character '\0'. Thus if my_var holds {'c','a','n','\0','s'}, then my_var looks like "can". But if the string does not end until it sees a null character. So if you fill a string character-by-character, you must append the '\0'. If you fill it with something like fgets, the null character is appended automatically. Also, note that '\0' is equal to zero.

Those are just easy howtos to get you started. As pmg said, we aren't here to do your homework for you, just give you tips. Look up fgets, printf, "strings in C", etc. If you get stuck, you can come back and ask a more specific question!


try this for c,

string FileMeasure="Hello FILE!"
int TempNumOne=FileMeasure.size();
char Filename[100];
for (int a=0;a<=TempNumOne;a++)
    {
        Filename[a]=FileMeasure[a];
    }

and try this for java,

String[] words = {"ace", "boom", "crew", "dog", "eon"};  

List<String> wordList = Arrays.asList(words);  

for (String e : wordList)  
{  
     System.out.println(e); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消