Please explain this specific line in my Java Code? - eclipse

I have just started learning Java and I reached till arrays , I was preparing this program(From a book) on replacing space ' ' with '.' (dots) and i am not able to understand this specific line (its not mentioned even in the book I am learning from).
Please help me out.
class SpaceRemover{
public static void main(String[] args){
String mostFamous = "Hey there stackoverFLow ";
char [] mf1 = mostFamous.toCharArray();
for(int dex = 0; dex<mf1.length;dex++)
{
char current = mf1[dex]; // What is happening in this line ??
if (current != ' ') {
System.out.print(current);
}
else{
System.out.print('.');
}
}
System.out.println();
}
}
Someone please explain what is happening in "char current = mf1[dex];"
Thanks a lot for your time.

You are getting the dexth character/item within the character array mf1 (hence mf1[dex]) and storing it into the local variable current.

Basically a String in java is an array of characters. So what the above code does is converts the string to an array of chars so that it can access each index of the array later on. Then the code enters into a for loop in order to iterate through all the indecies of the char array.
Assuming that that is already clear to you, the code now creates a char variable which holds the current index of the array.
char current = mf1[dex];
mf1 is your char array that represents the string. dex is the current index of the char that is determined by the for loop. So by doing this we can check each character (letter) of the char array. Now if the char "current" is a blank space we can replace it with a dot.

It's getting the character at index idx in the array mf1 and storing its value in the current variable.

The for-loop is iterating the string mostFamous character by character.
the line you are asking is to get the character at specific position. Function is similar to JavaScript's charAt(i)

char current = mf1[dex];
This line gets values from the mf1 char array and assign to the current variable according to the dex, dex works as index to the array element and it increments with the running loop.

The line
char current = mf1[dex];
is placed inside a for loop where the variable dex is incremented each time the loop is iterated. The variable dex is the zero-based index of the array. On the left hand side of the assignment operator (=), you are declaring a variable named current of type char. On the right hand side of the assignment operator you are accessing the dex-th character of your CharArray, if you start counting from zero. The assignment operator binds the variable you declared with the value of the character you specified on the right hand side.
For example, the first time the loop is run, dex would start at 0, hence mf1[dex] (or mf1[0]) is just 'H'.

Here is solution
class SpaceRemover{
public static void main(String[] args){
String mostFamous = "Hey there stackoverFLow ";
char [] mf1 = mostFamous.toCharArray();
// mf1 contains={'H', 'e','y',' ','t','h',.........}
for(char current: mf1)
{
//the for-each loop assigns the value of mf1 variable to the current variable
//At first time the 'H' is assigned to the current and so-on
System.out.print(current==' '?'.':current );
}
System.out.println();
}
}
}

It assigns the element of the char array mf1 at the index dex to the char variable current.
Note that the for loop and that line may be simplified by using the foreach syntax; these two code blocks are equivalent:
// Your code
for(int dex = 0; dex<mf1.length;dex++) {
char current = mf1[dex];
// Equivalent code
for (char current : mf1) {
But further, the whole method may be replaced by one line:
public static void main(String[] args){
System.out.println("Hey there stackoverFLow ".replace(" ", "."));
}

char current = mf1[dex];
this will return the char element in char array whose index is dex
This is quite a basic usage of array.
Good luck with your study.

After this statement, char [] mf1 = mostFamous.toCharArray();
mf1[0]=H, mf1[1]=e, mf1[1]=y...
so at this line, char current = mf1[dex];
so, in first iteration, current=H, second iteration current=e...

Related

Write a lex program that detects and counts the pattern that starts with an uppercase letter, ends with a lowercase letter

I understood the problem and written the below code. My code works and it prints the number of detected valid and invalid patterns when I quit the program with ctrl+z.
Here is my code:
%{
int valid = 0;
int invalid = 0;
%}
%%
([A-Z][a-zA-Z0-9]*[a-z])* {valid++;}
[a-zA-Z0-9]* {invalid++;}
%%
int yywrap(){}
int main(int argc, char **argv[])
{
printf("\n Enter inputs: \n\n");
yylex();
printf("\n\n\tNumber of VALID patterns = %d\n", valid);
printf("\tNumber of invalid patterns = %d\n\n", invalid);
return 0;
}
But I want something like this:
It should print the detected patterns, number of valid patterns and the number of invalid patterns whenever I input a new line.
There should be an EXIT command.
To achieve your goal, you should modify your code like this:
/*** Definition Section ***/
%{
int valid = 0;
int invalid = 0;
%}
/*** Rules Section ***/
%%
([A-Z][a-zA-Z0-9]*[a-z])* {printf("\n\tPattern Detected: %s ", yytext); valid++;}
[a-zA-Z0-9]* {invalid++;}
"\n" {
printf("\n\n\tNumber of VALID patterns = %d\n", valid);
printf("\tNumber of invalid patterns = %d\n\n", invalid);
valid = 0;
invalid = 0;
}
EXIT__ return 0;
%%
/*** User code section***/
int yywrap(){}
int main(int argc, char **argv[])
{
printf("\n Enter inputs: \n\n");
yylex();
return 0;
}
Here main change comes in the rule section.
Rule-1: ([A-Z][a-zA-Z0-9]*[a-z])* It detect and count valid patterns that starts with an uppercase letter, ends with a lowercase letter. In action, it prints the detected patterns and does the counting job too. Here yytext contains the text in the buffer, for this rule, it's the detected pattern.
Rule-2: [a-zA-Z0-9]* Keep a track of invalid patterns. It will help to prevent returning unmatched patterns.
Rule-3: "\n" It detects when you input a new line. In action, it prints the detected patterns, the number of valid patterns, and the number of invalid patterns whenever I input a new line. Also, reset the variables for counting to zero for the next line of input.
Rule-4: EXIT__ whenever you will input this exact command, the program will exit.
You can avoid printing the numbers of valid and invalid patterns inside the main function in the user code section.
But if you want to print the numbers of detected valid and invalid patterns at the end too, then this program will require a few modifications.

what is the substr? in the systemverilog

Int fd;
String str;
fd = $fopen(path, "r");
Status= $fgets(str, fd);
cm = str.substr(0,1);
cm1= str.substr(0,0);
I want to know what is substr function? What is the purpose above that??
The substr function returns a new string that is a substring formed by characters in position i through j of str. Very similar to examples posted here.
module test;
string str = "Test";
initial
$display(str.substr(0,1));
endmodule
The output will be:
>> Te
As you can see in section 6.16.8, IEEE SystemVerilog Standard 1800-2012.
substr function, as it name suggests, subtracts, or takes a chunk from a bigger string, in systemverilog.
Example:
stri0 = "my_lago";
stri1 = stri0.substr(1,5);
$display("This will give stri1 = %s" , stri1);
....
OUTPUT :- This will give stri1 = y_lag
Substring: This method extracts strings. It needs the Position of the substring ( start index, length). It then returns a new string with the characters in that range.
C# program Substring
using System;
class Program
{
static void Main()
{
string input = "ManCatDog";
// Get Middle three characters.
string subString = input.Substring(3, 6);
Console.WriteLine("SubString: {0}", subString);
}
}
Output
Substring: Cat

Trouble padding a Perl string array without increasing array length

I have an integer value my $reading = 1200;.
I have an array my #DigitField = "000000000";
I want to replace the right-hand 4 elements of the array with $reading's value, and I want to do this programmatically using Perl's length function as shown below.
I've tried.
my #DigitField = "000000000";
my $reading = 1200;
splice #DigitField, length(#DigitField) + 1, length $reading, $reading;
print #DigitField;
but I'm getting
0000000001200
and I want the string to remain nine characters wide.
What are some other ways to replace part of a Perl string array?
I think you are possibly confused - the # sigil indicates #DigitField is an array variable. A string is not an array.
I think you want to format the number:
my $reading = 1200;
my $digitfield = sprintf('%09d', $reading);
print $digitfield, "\n";
I added a \n to the end of the print, this adds a newline. Depending on the context of your program, you may or may not want this in the final.

How to return next string without >> with stringstream?

Instead of:
stringstream szBuffer;
szBuffer>>string;
myFunc(string);
How do I do like:
muFunc(szBuffer.NextString());
I dont want to create a temp var just for passing it to a function.
If you want to read the whole string in:
// .str() returns a string with the contents of szBuffer
muFunc(szBuffer.str());
// Once you've taken the string out, clear it
szBuffer.str("");
If you want to extract the next line (up to the next \n character), use istream::getline:
// There are better ways to do this, but for the purposes of this
// demonstration we'll assume the lines aren't longer than 255 bytes
char buf[ 256 ];
szBuffer.getline(buf, sizeof(buf));
muFunc(buf);
getline() can also take in a delimiter as a second parameter (\n by default), so you can read it word by word.

Why a for loop in this argument

for (int i=0; i<[rawNumber length]; i++) {
NSString* chr = [rawNumber substringWithRange:NSMakeRange(i, 1)];
if(doesStringContain(#"0123456789", chr)) {
telNumber = [telNumber stringByAppendingFormat:#"%#", chr];
}
}
What's the logic of this? What does this argument return?
Looks like it's stripping out all the non-numeric characters, to give you a plain old phone number.
I imagine telNumber is defined before this loop, and uses the value of telNumber somewhere else.
Lets say rawNumber held the following value: (987)-654-3210. The for loop runs 14 times total, since that's the length of rawNumber. Each time through, the code gets a single character - the first time it gets the first character, the second time the second character, etc. Each time through the loop, the code checks if the character is in the string 0123456789; if it is, then the code appends the character to the telNumber variable. If the character is not in the list of numbers (if it's ( or ) or - in our example), then it's just discarded.