-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_reverse_except_special_char.c
More file actions
81 lines (69 loc) · 1.56 KB
/
string_reverse_except_special_char.c
File metadata and controls
81 lines (69 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/************************************************
* creator: vingc zhang
* time: 2017.03.24
*************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
Given a string, that contains special character together with alphabets (¡®a¡¯ to ¡®z¡¯ and ¡®A¡¯ to ¡®Z¡¯),
reverse the string in a way that special characters are not affected.
Examples:
Input: str = "a,b$c"
Output: str = "c,b$a"
Note that $ and , are not moved anywhere.
Only subsequence "abc" is reversed
Input: str = "Ab,c,de!$"
Output: str = "ed,c,bA!$"
*/
#define true 1
#define false 0
#define MAX_LEN 100
int isAlphabet( char ch )
{
if( ( ch >= 'a' && ch <= 'z' ) ||
( ch >= 'A' && ch <= 'Z' ) )
{
return true;
}
return false;
}
void reverseExSpec( char * str )
{
int strLen = strlen( str );
int i,j;
char tmp;
i = 0;
j = strLen - 1;
while( i < j )
{
/* swap the char and skip the special char */
if( ! isAlphabet( str[i] ) )
{
i++; //skip special
}
else if( ! isAlphabet( str[j] ) )
{
j--; //skip special
}
else
{
//swap
tmp = str[j];
str[j] = str[i];
str[i] = tmp;
//move on
i++;
j--;
}
}
printf( "rev: %s\n", str );
return;
}
void main( void )
{
char str[ MAX_LEN ];
//snprintf( str, MAX_LEN, "%s", "a,b$c" );
snprintf( str, MAX_LEN, "%s", "Ab,c,de!$" );
reverseExSpec( str );
}