03-30-2022 10:51 AM
Hello,
I have a string like this : "ABCDEF"
I want to get this from this string : "EFCDAB".
What's the best way to do that in CVI ?
Thanks in advance,
Blue
03-30-2022 11:47 AM
You are reversing 16bit words, not bytes here.
03-31-2022 02:21 AM
Something along this line? (str1 and str2 must be previously allocated in the correct size)
for (i = 0; i < strlen (str1); i++) {
str2[i] = str1[strlen (str1) - i - 1];
}
03-31-2022 02:55 AM - edited 03-31-2022 02:57 AM
This is more a C question than a CVI question... You can do this in place without need for an extra allocation by using an intermediate short. Something like (untested, caveat if string len is odd, caveat if UTF, etc)
char Str[]="ABCDEF";
int L=strlen(Str);
short C, *SC=(short*)Str;
for (int i=0; i<L/4; i++) {
C=SC[i];
SC[i]=SC[L/2-i];
SC[L/2-i]=C;
}
03-31-2022 03:02 AM
Hello,
Roberto, this will gave me "FEDCBA" and not "EFCDAB".
03-31-2022 03:04 AM
Hello gdargaud,
I will try this, thank you.
03-31-2022 03:15 AM
@BlueAnaconda ha scritto:
Hello,
Roberto, this will gave me "FEDCBA" and not "EFCDAB".
Correct, I didn't focused on expected target string and the quotes around "reverse"
03-31-2022 06:13 AM
gdargaud,
The code I tested, it's not good too.
Roberto, Yes, do you have a suggestion please ?
03-31-2022 08:14 AM
This should work for any string with any number of couples of chars.
The lack of explanations and comments is not casual. 🤣
char *s = "ABCDEF";
int len = (int)strlen(s);
int len2 = (len / 4) * 2; // ;-)
char c1, c2;
for (int i=0; i<len2; i+=2) {
c1 = s[i];
c2 = s[i+1];
s[i] = s[len-2-i];
s[i+1] = s[len-1-i];
s[len-2-i] = c1;
s[len-1-i] = c2;
}
03-31-2022 10:31 AM
You can also make use of SwapBlock function in the Programmer's Toolbox:
#include "toolbox.h"
#include <ansi_c.h>
static int i, len, duplets;
static char str[64];
strcpy (str, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
len = strlen (str);
duplets = len / 2;
for (i = 0; i < duplets; i += 2) {
SwapBlock (str + i, str + len - i - 2, 2);
}
Just my 2c... after my initial gaffe 😉